onResponse hook
Runs after the response has been fully sent to the client.
Syntax
app.addHook('onResponse', async (request, reply) => {}) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
request | FastifyRequest | No | The completed request. |
reply | FastifyReply | No | The reply, with statusCode and elapsedTime set. |
Returns
void | Promise<void> — Side-effect only; cannot modify the response.
Examples
import Fastify from 'fastify';
const app = Fastify({ logger: true });
app.addHook('onResponse', async (req, reply) => {
req.log.info({
status: reply.statusCode,
ms: reply.elapsedTime,
route: req.routeOptions.url,
}, 'request completed');
});
Notes
The response is already flushed, so this hook is for metrics, audit
logging, and cleanup only. reply.elapsedTime gives the handler duration
in milliseconds.