app.addHook()

Registers a lifecycle hook that runs at a specific phase of every request or the app lifecycle.

Since Fastify 5 Spec ↗

Syntax

app.addHook(name, handler)

Parameters

NameTypeRequiredDescription
name string No A hook name such as onRequest, preHandler, onSend, or onClose.
handler Function No Async function for the chosen phase.

Returns

FastifyInstance — The instance, for chaining.

Examples

import Fastify from 'fastify';

const app = Fastify();

app.addHook('onRequest', async (req) => {
  req.log.info({ url: req.url }, 'incoming');
});

app.addHook('onResponse', async (req, reply) => {
  req.log.info({ ms: reply.elapsedTime }, 'completed');
});

Notes

Hooks added at the top level run for all routes; hooks inside a plugin are encapsulated to that scope. Throwing in a request hook short-circuits to the error handler.