preHandler hook
Runs after validation, just before the route handler executes.
Syntax
app.addHook('preHandler', async (request, reply) => {}) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
request | FastifyRequest | No | The validated request. |
reply | FastifyReply | No | The reply object. |
Returns
void | Promise<void> — Throw or send to short-circuit.
Examples
import Fastify from 'fastify';
const app = Fastify();
const requireAdmin = async (req, reply) => {
if (req.user?.role !== 'admin') {
reply.code(403).send({ error: 'Forbidden' });
}
};
app.delete('/cats/:id', { preHandler: requireAdmin }, async () => ({
deleted: true,
}));
Notes
The body is parsed and validated here, making preHandler the right place
for authorization and resource loading. Route-level preHandler arrays run
in order before the handler.