# Lifecycle Hooks — Fastify

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

> Run code at specific points in the request/response cycle.

## Hook points in Fastify

Fastify provides hooks for: `onRequest`, `preValidation`, `preHandler`, `onSend`, `onResponse`, and more. Use them to run middleware-like logic or intercept requests.

## Common hooks

Register hooks globally or per-route. They run in sequence and can modify request/response.

```javascript
// Global hook: log every request
fastify.addHook('onRequest', async (request, reply) => {
  console.log(`${request.method} ${request.url}`);
});

// Global hook: add timing header
fastify.addHook('onSend', async (request, reply, payload) => {
  reply.header('X-Response-Time', `${Date.now() - request.startTime}ms`);
  return payload;
});

// Per-route hook: validate auth token
fastify.get('/admin', 
  { onRequest: async (req, reply) => {
    const token = req.headers.authorization;
    if (!token) return reply.status(401).send({ error: 'Unauthorized' });
  }},
  async () => ({ message: 'Admin access granted' })
);
```

**Quiz:** Which hook runs after a request is validated but before the handler?

- [ ] onRequest
- [ ] preValidation
- [x] preHandler

*Answer:* preHandler. preHandler runs after validation and before the route handler. Use it for auth checks or last-minute data preparation.
