reply.code / send / header / redirect / type
The Reply Object
When you need fine control over status, headers, redirects, or content type, the reply object exposes everything you need.
What you'll learn
- Set status with reply.code
- Set headers with reply.header
- Redirect, change content type, or stream a body
reply is Fastify’s wrapper around Node’s http.ServerResponse. It is chainable and async-safe.
Status & Headers
app.post('/items', async (req, reply) => {
const item = await createItem(req.body);
reply
.code(201)
.header('Location', `/items/${item.id}`)
.header('X-Trace', req.id);
return item;
}); reply.code sets the status. reply.header appends one header; reply.headers({ ... }) sets
several at once.
Redirects
app.get('/old', async (req, reply) => {
return reply.redirect('/new', 301);
}); redirect(url, code?) defaults to 302. The handler can return the call directly.
Content Type & Streams
import { createReadStream } from 'node:fs';
app.get('/report.xml', async (req, reply) => {
reply.type('application/xml');
return createReadStream('./report.xml');
}); When the return value is a Node stream, Fastify pipes it to the response without buffering.
When to Use Reply vs Return
Return a value when you just want JSON with 200 OK. Reach for reply whenever you need a
non-default status, custom headers, a redirect, a stream, or a non-JSON content type.