Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 39 ยท Getting Started

Server Options and Logging

Configure Fastify with server options (logger, bodyLimit, trustProxy, timeouts, request ids) and learn structured Pino logging: levels, child loggers and redaction.

Fastify() accepts an options object that tunes the server and its defaults. Most projects set only a few of them, but you should know what exists, because the right option often replaces a hand-written workaround. Logging deserves special attention: Fastify ships with the fast Pino logger, which produces structured JSON logs that log platforms can search and graph.

The options you will use most

JavaScript
import Fastify from 'fastify';

const app = Fastify({
  logger: true,                 // structured logs with Pino
  bodyLimit: 1_048_576,         // max request body in bytes (default 1 MiB)
  maxParamLength: 100,          // max length of a URL parameter (default 100)
  trustProxy: false,            // read X-Forwarded-* headers? (see below)
  ignoreTrailingSlash: false,   // treat /users and /users/ as the same route
  caseSensitive: true,          // /Users and /users are different routes
  requestTimeout: 0,            // ms to receive the whole request (0 = no limit)
  connectionTimeout: 0,         // ms before an idle socket is closed
  keepAliveTimeout: 72_000,     // ms to keep idle keep-alive sockets open
});
Option Why you would change it
logger Turn logging on, set its level, redact secrets, change output
bodyLimit Raise it for uploads; lower it for small JSON APIs to resist abuse
trustProxy Behind a load balancer, so request.ip and request.protocol use X-Forwarded-*
ignoreTrailingSlash Accept /users/ as /users instead of returning 404
caseSensitive Set false to treat /Users like /users
genReqId, requestIdHeader, requestIdLogLabel Control request ids (see below)
disableRequestLogging Stop the automatic "incoming request"/"request completed" lines
http2, https Serve HTTP/2 or TLS directly (usually done at the proxy instead)
routerOptions Router tuning such as maxParamLength and ignoreTrailingSlash in newer versions

Option names move around between major versions (several router options were grouped under routerOptions in Fastify 5.5+, with the old top-level names deprecated). Check the version you use before copying an option from a blog post; the Fastify reference lists every option for each major version.

trustProxy is a security setting. When it is true, Fastify believes the X-Forwarded-For header, so any client can claim to be any IP. Enable it only when your app is reachable only through a proxy you control, and prefer a number of hops (1) or a list of proxy addresses instead of a blanket true.

Why bodyLimit matters

Without a limit, an attacker could send a huge body and exhaust memory. Fastify rejects bodies larger than bodyLimit with a 413 Payload Too Large error before parsing them. The default of 1 MiB suits JSON APIs; raise it deliberately for routes that really need more (you can also set bodyLimit on a single route).

Logging with Pino

Setting logger: true gives you three things:

  1. An automatic log line for each incoming request and each completed response, with timing.
  2. app.log for messages that are not tied to a request.
  3. request.log inside handlers, a child logger that adds the request id to every line, so you can find every line that belongs to one request.

A real Fastify log line looks like this (read-only sample; the fields come from Pino, and values differ on your machine):

JSON
{"level":30,"time":1760000000000,"pid":4120,"hostname":"api-1","reqId":"req-1","req":{"method":"GET","url":"/hello","host":"localhost:3000"},"msg":"incoming request"}
{"level":30,"time":1760000000003,"pid":4120,"hostname":"api-1","reqId":"req-1","res":{"statusCode":200},"responseTime":2.7,"msg":"request completed"}

level is a number: 10 trace, 20 debug, 30 info, 40 warn, 50 error, 60 fatal. Pino writes JSON because machines read logs far more than people do. For readable local output you pipe it through pino-pretty (node server.js | npx pino-pretty) or configure a transport in development only.

JavaScript
const app = Fastify({
  logger: {
    level: process.env.LOG_LEVEL || 'info',
    redact: ['req.headers.authorization', 'req.headers.cookie'],
  },
});

level hides messages below it. redact replaces the listed paths with [Redacted], so tokens and cookies never reach your log storage. Pass the level from an environment variable so you can turn on debug in production for a short time without a deploy.

Using the logger in handlers

JavaScript
app.get('/orders/:id', async (request) => {
  request.log.info({ orderId: request.params.id }, 'loading order');
  const order = await loadOrder(request.params.id);
  if (!order) request.log.warn('order not found');
  return order ?? { found: false };
});

The first argument can be an object whose fields are merged into the JSON; the second is the message. Put data in the object instead of string-concatenating it into the message, so log tools can filter on orderId.

Node.js request.log and app.log in the stand-in

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.

The stand-in prints simple [log] lines; real Pino prints JSON objects as shown above.

How child loggers and redaction work

To see why structured logging is handy, here is a small stand-in for Pino's key ideas: levels, bound fields on child loggers, and redaction. This is not Pino; it only reproduces the behavior.

Node.js A mini logger: levels, child loggers, redact

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.

Notice that every line from the child carries reqId, the secret header is replaced, and the debug line is dropped.

Request ids

Each request gets an id, req-1, req-2, ... by default. In a system with several services you want one id to travel through all of them. Options:

  • requestIdHeader: 'x-request-id' reuses the id sent by the caller or proxy.
  • genReqId: (req) => crypto.randomUUID() generates your own ids.
  • requestIdLogLabel: 'requestId' renames the field in the logs.

request.id gives you the id in code, for example to return it in an error body so users can quote it to support.

Common mistakes

  • Logging secrets (passwords, tokens). Use redact and never log whole request bodies by default.
  • Using console.log in handlers. It lacks levels and request ids, and is slower under load.
  • Leaving trustProxy: true on a server that is directly reachable.
  • Raising bodyLimit globally for one upload route instead of setting it on that route.
  • Copying options from an old article without checking the Fastify version.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does request.log add compared with app.log?

    request.log is a child logger bound to the request, so each line includes its reqId.
  2. 2. What does the redact option do?

    Redaction hides secrets such as Authorization headers before logs are written.
  3. 3. With level 'info', which message is dropped?

    Levels below the configured one (trace and debug here) are ignored.
  4. 4. When is trustProxy safe to enable?

    Otherwise clients can forge X-Forwarded-For. Prefer a hop count or proxy addresses.

Summary

  • Server options tune limits, routing behavior, timeouts, request ids and logging.
  • bodyLimit defaults to 1 MiB; raise it per route when needed.
  • trustProxy changes how client IPs are read: enable it carefully.
  • logger: true enables structured Pino logs; use request.log in handlers and redact for secrets.
  • Read option names against your Fastify version; some moved between releases.

Next: Project Structure and Configuration