Hooks and the request lifecycle

Ninth chapter of the "Fastify with TypeScript" series. Hooks are Fastify's equivalent of middleware, but with a well-defined execution order and much finer granularity. Rather than memorize that order from a diagram, we'll make the application print it.

The lifecycle

Every request goes through the same sequence of stages, and you can attach a function, a hook, to each of them:

onRequest → preParsing → preValidation → preHandler → handler → preSerialization → onSend → onResponse 

Watch it happen

Add this at the top of the userRoutes plugin in src/users/users.route.ts, just before the users array. It is temporary: we'll delete it at the end of the chapter.

 // Temporary: print the name of each lifecycle stage as a request goes through it const stages = [ 'onRequest', 'preParsing', 'preValidation', 'preHandler', 'preSerialization', 'onSend', 'onResponse', ] as const; for (const stage of stages) { fastify.addHook(stage, async () => { console.log(stage); }); } fastify.addHook('onError', async (request, reply, error) => { console.log('onError:', error.message); }); 

Create a user with the curl command from chapter 7 and look at the server's terminal:

onRequest preParsing preValidation preHandler preSerialization onSend onResponse 

Now send an invalid body, -d '{"name":"Grace"}':

onRequest preParsing preValidation onError: body must have required property 'email' onSend onResponse 

Validation happens between preValidation and preHandler. The request failed there, so preHandler, the handler itself and preSerialization never ran. Fastify went straight to onError and then sent the error response, which still passes through onSend and onResponse.

Finally, curl localhost:3000/health prints nothing. The hooks were added inside the users plugin, and /health is declared outside it: encapsulation, exactly as in the previous chapter.

What each stage is for

  • onRequest: the request has just arrived and the body hasn't been read yet. The place for authentication and rate limiting, because a rejected request costs almost nothing.
  • preParsing: the raw body stream, before it is parsed. Rarely needed (decompression, decryption).
  • preValidation: the body is parsed but not validated yet. Use it to normalize input before the schema sees it.
  • preHandler: everything is validated and typed. Use it for checks that need request.body or request.params, such as "is this user allowed to edit this resource?".
  • preSerialization: receives the value the handler returned, before it is turned into JSON.
  • onSend: last chance to touch the serialized payload or the headers.
  • onResponse: the response has been sent. Good for metrics and timing.
  • onError: runs when something threw, before the error handler builds the response. Use it to observe the error (log it, report it), not to change the reply.

Three examples, one per kind of job:

// preValidation: normalize the input before the schema sees it fastify.addHook('preValidation', async (request) => { const body = request.body; if (body && typeof body === 'object' && 'email' in body && typeof body.email === 'string') { body.email = body.email.trim().toLowerCase(); } }); // preSerialization: change the payload the handler returned fastify.addHook('preSerialization', async (request, reply, payload: unknown) => { if (payload && typeof payload === 'object' && !Array.isArray(payload)) { return { ...payload, servedAt: new Date().toISOString() }; } return payload; }); // onResponse: the response is gone, measure it fastify.addHook('onResponse', async (request, reply) => { request.log.info({ ms: reply.elapsedTime }, 'Request completed'); }); 

Notice the types. In preValidation nothing has been validated yet, so request.body is unknown and has to be narrowed with typeof and in before you touch it. The same goes for payload in preSerialization. Don't reach for a cast here: these are exactly the places where the data is not guaranteed to be what you expect.

Stopping a request from a hook

A hook can answer the request itself, and then the rest of the lifecycle is skipped. The cleanest way is to throw an error: Fastify stops and the error handler produces the response (that's the next chapter). The other way is to send the reply yourself:

fastify.addHook('onRequest', async (request, reply) => { if (!request.headers.authorization) { return reply.code(401).send({ error: 'Unauthorized' }); } }); 

As we saw in the previous chapter, return the reply when you send it from an async hook, so Fastify knows the request has been answered.

Route-level hooks

Hooks don't have to apply to a whole plugin. Any route can declare its own, as an array in its options:

fastify.get('/admin', { onRequest: [async (request, reply) => { if (request.headers['x-admin'] !== 'yes') { return reply.code(403).send({ error: 'Forbidden' }); } }], }, async () => ({ admin: true })); 

This is how we'll attach authentication in chapter 12: the check is written once, as a reusable function, and each route that needs it lists it in onRequest.

Application lifecycle hooks

Two more hooks are about the application rather than a request:

fastify.addHook('onReady', async function () { this.log.info('All plugins loaded, ready to accept connections'); }); fastify.addHook('onClose', async function () { this.log.info('Closing'); }); 

onReady runs once, when every plugin has been loaded. onClose runs when app.close() is called. Plugins that hold a resource use it to release it: the database plugin we'll add in chapter 13 closes its connections there, and graceful shutdown in chapter 18 relies on it.

Clean up

Delete the temporary block from users.route.ts. The project is back to where chapter 8 left it, and you now know where each piece of the next chapters plugs in: error handling in the onError path, authentication in onRequest.

⬅️ Previous chapter: Plugins and encapsulation · ➡️ Next chapter: Error handling

This article is part of the "Fastify with TypeScript" series — chapter 9 of 18.