Hooks
Fastify allows you to listen to specific events in the application or request/response lifecycle.
By using hooks you can interact directly with the lifecycle of Fastify.
Available Hooks
Request/Reply
- onRequest
- preParsing
- preValidation
- preHandler
- preSerialization
- onError
- onSend
- onResponse
- onTimeout
- onRequestAbort
Application
Registering Hooks
Hooks can be registered at providers by simply exporting a function with their respective name.
ts
import type { FastifyReply, FastifyRequest } from 'fastify';
export type MyProvider = true;
export default function (): MyProvider {
return true;
}
// These functions must respect their parameter signature
// read more in the official Fastify documentation
// https://fastify.dev/docs/latest/Reference/Hooks
export async function onRequest(request: FastifyRequest, reply: FastifyReply) {
// Your logic here
}
1
Example
A good example to demonstrate how hooks can be used is with Prisma or any other ORM that you are using.