app.decorateRequest()
Adds a property or method to every request object.
Syntax
app.decorateRequest(name, value) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
name | string | No | The property name added to FastifyRequest. |
value | any | No | A default value, getter, or null placeholder for per-request data. |
Returns
FastifyInstance — The instance, for chaining.
Examples
import Fastify from 'fastify';
const app = Fastify();
app.decorateRequest('user', null);
declare module 'fastify' {
interface FastifyRequest {
user: { id: string } | null;
}
}
app.addHook('preHandler', async (req) => {
req.user = { id: 'u_1' };
});
Notes
Decorate with a primitive or null placeholder rather than an object
literal so each request gets its own value. Populate the field in a hook
such as preHandler.