Lesson 14 / 32

Middleware & Hooks Pattern

Implement logging, authentication and rate limiting with Fastify hooks instead of classic middleware chains.

By · 15 years in web development · Updated 1 Oct 2026

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;
});