Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 39 ยท Routes and Handlers

The Fastify Reply Object

Master the Fastify reply object: status codes, headers, content types, send() with strings, objects and buffers, redirects, and the async return rules.

If request is what the client sent, reply is how you answer. You can often ignore it, because returning a value from an async handler is enough. But as soon as you need a status other than 200, custom headers, a redirect or a different content type, you reach for the reply.

Most reply methods return the reply itself, so you chain them: reply.code(201).header('location', '/x').send(data).

The essential methods

Method What it does
reply.code(n) / reply.status(n) Sets the status code
reply.header(name, value) Sets one header (reply.headers({...}) sets many)
reply.type(mime) Sets Content-Type
reply.send(payload) Sends the response
reply.redirect(url, code?) Sends a redirect (302 by default)
reply.getHeader(name) Reads a header you already set
reply.sent true once a response has been started
reply.raw Node's ServerResponse (escape hatch)

Chaining: code, header, type and send all return reply, so there is rarely a need for temporary variables.

Two ways to answer

JavaScript
// 1. Return the payload from an async handler
app.get('/a', async () => ({ ok: true }));

// 2. Call reply.send()
app.get('/b', async (request, reply) => {
  return reply.send({ ok: true });
});

They produce the same response. Use the first when you only need the default status and headers; use the second (or both together, see below) when you want to adjust the status or headers.

Node.js Status codes and headers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Choose status codes deliberately: 200 for success with a body, 201 for created resources (with a Location header), 204 for success without a body, 400 for invalid input, 401 for missing authentication, 403 for forbidden, 404 for missing resources, 409 for conflicts and 422 for semantic validation failures if you prefer it over 400.

What send() accepts

send() looks at the payload type and picks a content type for you, unless you set one:

Payload Content-Type Notes
Object or array application/json; charset=utf-8 Serialized with JSON.stringify, or with a response schema
String text/plain; charset=utf-8 Set type('text/html') for HTML
Buffer application/octet-stream Binary data
Stream application/octet-stream Piped to the client (files, proxies)
Error JSON error body Same as throwing
undefined / empty no body Often paired with code(204)
Node.js Strings, objects and custom types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Pitfall: if you send a string that contains JSON, Fastify treats it as plain text (text/plain), not JSON. Either send an object, or set reply.type('application/json') yourself.

Redirects

JavaScript
app.get('/old', async (request, reply) => reply.redirect('/new'));            // 302
app.get('/moved', async (request, reply) => reply.redirect('/new', 301));     // permanent

Use 301/308 for permanent moves (browsers and search engines remember them), 302/307 for temporary ones, and 303 to send a client to a result page after a POST. In Fastify 5 the call is reply.redirect(url, code); older versions accepted the arguments in the opposite order.

Node.js Redirect with a Location header

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Async rules you must know

Fastify supports two styles at once, so there is one rule to follow: in an async handler, either return the payload or call reply.send(), and if you call send, also return reply (or await it).

JavaScript
// Good: return the value
app.get('/ok1', async () => ({ ok: true }));

// Good: send and return the reply
app.get('/ok2', async (request, reply) => {
  return reply.code(201).send({ ok: true });
});

// Bad: send inside a callback without returning the reply
app.get('/bad', async (request, reply) => {
  setTimeout(() => reply.send({ ok: true }), 10);   // handler already resolved with undefined
});

In the bad example the handler's promise resolves with undefined immediately. Fastify then assumes you have nothing to send and logs an error (Promise may not be fulfilled with 'undefined' when statusCode is not 204). If you must send from a callback, wrap the callback in a promise and await it, or return reply so Fastify knows to wait.

Also avoid doing both reply.send(x) and return y with a different value: the first call wins and Fastify warns about the second.

Sending files and streams

For streams, set the type and pass the stream to send():

JavaScript
import { createReadStream } from 'node:fs';

app.get('/report', async (request, reply) => {
  return reply.type('text/csv').send(createReadStream('./report.csv'));
});

For serving whole directories, use the official @fastify/static plugin; it handles caching headers, ranges and path traversal safely, which a hand-written file route will not.

Headers worth knowing

JavaScript
reply.header('Cache-Control', 'public, max-age=3600');
reply.header('Content-Disposition', 'attachment; filename="report.csv"');
reply.header('X-Request-Id', request.id);

Header names are case-insensitive, and Fastify lowercases them when sending. Setting a header twice replaces it; for multiple values (like cookies) pass an array.

Common mistakes

  • Sending twice (for example reply.send() then return reply.send()). The second attempt logs a warning and does nothing.
  • Returning a string of JSON and expecting a JSON content type.
  • Forgetting return before reply.send() in an async function that awaits something afterwards.
  • Using reply.raw.end() directly. It bypasses hooks, serialization and logging.
  • Returning undefined from a handler with the default 200 status.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which call gives a 201 response with a JSON body?

    code() sets the status, send() sets the body, and returning the reply tells Fastify the response is handled.
  2. 2. What Content-Type does Fastify use when you send a plain string?

    Strings default to text/plain; use reply.type to change it.
  3. 3. What is the problem with calling reply.send() inside a setTimeout callback of an async handler without returning reply?

    Return the reply or await a promise so Fastify waits for the late send.
  4. 4. Which redirect call is correct in Fastify 5 for a permanent redirect?

    Fastify 5 uses redirect(url, code); the code defaults to 302.

Summary

  • reply.code(), header(), type() and send() chain; return the reply (or the payload) from async handlers.
  • Objects become JSON, strings become text, buffers and streams are binary.
  • Use meaningful status codes: 201 with Location, 204 without a body, 4xx for client errors.
  • reply.redirect(url, code) sends redirects; permanent ones use 301 or 308.
  • Avoid double sends and sends from un-awaited callbacks.

Next: Async Handlers and Error Handling