# Middleware & Hooks Pattern — Fastify

Source: https://www.geekswithgeeks.com/en/fastify/ff-middleware

> 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.

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