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
Enter fullscreen mode
Exit fullscreen mode
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 .…