Hooks
Hooks
Hooks are registered with the fastify.addHook method and allow you to listen
to specific events in the application or request/response lifecycle. You have to
register a hook before the event is triggered, otherwise, the event is lost.
By using hooks you can interact directly with the lifecycle of Fastify. There are Request/Reply hooks and application hooks:
- Request/Reply Hooks
- Application Hooks
- Scope
- Route level hooks
- Using Hooks to Inject Custom Properties
- Diagnostics Channel Hooks
ℹ️ Note: The
donecallback is not available when usingasync/awaitor returning aPromise. If you do invoke adonecallback in this situation unexpected behavior may occur, e.g. duplicate invocation of handlers.
Request/Reply Hooks
Request and Reply are the core Fastify objects.
done is the function to continue with the lifecycle.
It is easy to understand where each hook is executed by looking at the lifecycle page.
Hooks are affected by Fastify's encapsulation, and can thus be applied to selected routes. See the Scopes section for more information.
There are eight different hooks that you can use in Request/Reply (in order of execution):
onRequest
fastify.addHook('onRequest', (request, reply, done) => {
// Some code
done()
})
Or async/await:
fastify.addHook('onRequest', async (request, reply) => {
// Some code
await asyncMethod()
})
ℹ️ Note: In the onRequest hook,
request.bodywill always beundefined, because the body parsing happens before the preValidation hook.
preParsing
If you are using the preParsing hook, you can transform the request payload
stream before it is parsed. It receives the request and reply objects as other
hooks, and a stream with the current request payload.
If it returns a value (via return or via the callback function), it must
return a stream.
For instance, you can decompress the request body:
fastify.addHook('preParsing', (request, reply, payload, done) => {
// Some code
done(null, newPayload)
})
Or async/await:
fastify.addHook('preParsing', async (request, reply, payload) => {
// Some code
await asyncMethod()
return newPayload
})
ℹ️ Note: In the preParsing hook,
request.bodywill always beundefined, because the body parsing happens before the preValidation hook.
ℹ️ Note: You should also add a
receivedEncodedLengthproperty to the returned stream. This property is used to correctly match the request payload with theContent-Lengthheader value. Ideally, this property should be updated on each received chunk.
ℹ️ Note: The size of the returned stream is checked to not exceed the limit set in
bodyLimitoption.