Declaring hooks
In the previous section, we saw that a server-side application usually has two main lifecycles. So, being a hook-based web framework and following its philosophy of giving complete control to developers, Fastify emits a specific event every time it advances to the next phase. Furthermore, these phases follow a rigid and well-defined execution order. Knowing it enables us to add functionality at a specific point during the boot or the execution of our application.
One essential and beneficial side effect of this approach is that, as developers, we don’t care about the declaration order of our hooks since the framework guarantees that they will be invoked at the right moment in time.
The mechanism described works because Fastify, under the hood, defines a “hook runner” that runs the callback functions declared for every known event. As developers, we need a method to attach our hooks to the Fastify instance. The addHook
hook allows us to do...