Lesson 14 / 30
Middleware & Hooks Pattern
Implement cross-cutting concerns like logging, authentication, and rate limiting.
Why hooks instead of middleware?
Fastify's hooks are more explicit and performant than traditional middleware chains. Each hook has a clear role in the request lifecycle.
Logging middleware with hooks
Use onRequest to log incoming, onSend to log outgoing.
fastify.addHook('onRequest', async (request, reply) => {
request.startTime = Date.now();
});
fastify.addHook('onSend', async (request, reply, payload) => {
const duration = Date.now() - request.startTime;
fastify.log.info({
method: request.method,
url: request.url,
statusCode: reply.statusCode,
duration,
});
return payload;
});