Menu

Hooks and the request lifecycle — Fastify with TypeScript (part 9/18)
📰

Hooks and the request lifecycle — Fastify with TypeScript (part 9/18)

DEV Community: fastify·Antonio Tripodi·10 days ago
#wT9P9Kdd
#devtofastify#devto#dev#request#fastify
Long article (1198 words) — no AI summary yet.
Reading 0:00
15s threshold

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

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.