onRequest hook
Runs first in the request lifecycle, before body parsing and validation.
Syntax
app.addHook('onRequest', async (request, reply) => {}) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
request | FastifyRequest | No | The incoming request (body not yet parsed). |
reply | FastifyReply | No | The reply object. |
Returns
void | Promise<void> — Throw or send to short-circuit.
Examples
import Fastify from 'fastify';
const app = Fastify();
app.addHook('onRequest', async (req, reply) => {
if (!req.headers.authorization) {
reply.code(401).send({ error: 'Unauthorized' });
}
});
Notes
request.body is undefined here because parsing has not run yet. Ideal for
authentication, rate limiting, and request logging. Sending a reply or
throwing stops the pipeline.