Understanding the application lifecycle
The application lifecycle covers the boot process and the execution of our application server. In particular, we refer to loading the plugins, adding routes, making the HTTP server run, and eventually closing it. Fastify will emit four different events, allowing us to interact with the behavior of every phase:
onRoute
onRegister
onReady
onClose
Now, for every event of the previous list, let’s check the respective callback signature and most common use cases.
The onRoute hook
The onRoute
hook event is triggered every time a route is added to the Fastify instance. This callback is a synchronous function that takes one argument, commonly called routeOptions
. This argument is a mutable object reference to the route declaration object itself, and we can use it to modify route properties.
This hook is encapsulated and doesn’t return any value. Therefore, one of the most common use cases is adding route...