preSerialization hook

Runs after the handler returns a payload but before it is serialized.

Since Fastify 5 Spec ↗

Syntax

app.addHook('preSerialization', async (request, reply, payload) => any)

Parameters

NameTypeRequiredDescription
request FastifyRequest No The request object.
reply FastifyReply No The reply object.
payload any No The value returned by the handler.

Returns

any — The (possibly transformed) payload to serialize.

Examples

import Fastify from 'fastify';

const app = Fastify();

app.addHook('preSerialization', async (_req, _reply, payload) => {
  return { data: payload, meta: { ts: Date.now() } };
});

app.get('/cats', async () => ['kitty']);

Notes

Receives the object payload (not strings, buffers, or streams). Return a new object to wrap or reshape responses globally. Runs before onSend.