Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Routes and Handlers

The Fastify Request Object

Tour the Fastify request object: reading the JSON body, headers, params, query, method, URL, id and client IP, plus body parsing errors and content types.

Every handler receives a request as its first argument. It is a lightweight wrapper around Node's incoming message, plus the parsed pieces you actually want. Learning exactly what is on it, and what type each property has, saves a lot of debugging.

The properties you will use

Property Meaning Example
request.params Path parameters { id: '42' }
request.query Parsed query string { page: '2' }
request.body Parsed body (POST, PUT, PATCH) { name: 'Ada' }
request.headers Headers, names in lowercase { 'content-type': '...' }
request.method HTTP method, uppercase 'POST'
request.url Path and query as sent '/users?page=2'
request.id Unique request id 'req-1'
request.ip Client address (respects trustProxy) '203.0.113.7'
request.log Child logger bound to this request request.log.info(...)
request.routeOptions The matched route's url, method, config, ... request.routeOptions.url
request.raw Node's IncomingMessage for streams and low-level needs
request.server The Fastify instance handling the route request.server.config

Two points deserve emphasis. First, header names are always lowercase (request.headers['content-type'], never Content-Type), because HTTP headers are case-insensitive and Node normalizes them. Second, request.routeOptions.url is the route pattern (/users/:id), while request.url is the actual URL (/users/42). Use the pattern for metrics labels, because the actual URL has unbounded variety.

Node.js Inspecting a request

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 header was sent as X-Client and read back as x-client. The contentType was added because payload was an object (the test helper serialized it as JSON).

Reading the body

By default Fastify understands two content types:

Content-Type request.body becomes
application/json The parsed JavaScript value
text/plain A string

Other types, such as HTML forms (application/x-www-form-urlencoded) and file uploads (multipart/form-data), need an official plugin (@fastify/formbody, @fastify/multipart). If a request arrives with a content type Fastify cannot parse, it answers 415 Unsupported Media Type automatically. You can teach Fastify new types with app.addContentTypeParser('application/xml', parseFn); that API is read-only here.

Body parsing rules worth knowing:

  • Bodies are read for POST, PUT, PATCH (and OPTIONS, DELETE in some setups); GET and HEAD have no body.
  • The body size is limited by bodyLimit (1 MiB by default); larger requests get 413.
  • Invalid JSON produces a 400 with the code FST_ERR_CTP_INVALID_JSON_BODY, before your handler runs.
  • A request that says it is JSON but has an empty body produces 400 with FST_ERR_CTP_EMPTY_JSON_BODY.
  • Because the body is parsed before your handler, your code never has to wrap JSON.parse in try/catch.
Node.js Body parsing and its errors

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 the error code for failing cases. In real Fastify the message also includes the details of the parse failure. Clients get 400 Bad Request: the mistake is theirs, not the server's.

Headers

Headers carry authentication, content negotiation, caching hints and tracing ids. Typical reads:

JavaScript
const auth = request.headers.authorization;        // 'Bearer abc...'
const accepts = request.headers.accept;
const lang = request.headers['accept-language'];
const traceId = request.headers['x-request-id'];

A missing header is undefined. Header values are strings (or arrays of strings for repeated headers such as set-cookie). Never trust a header for security decisions unless you verify it (a signed token, for example): clients can send anything. In particular x-forwarded-for is only meaningful behind a proxy you control, as explained in Server Options and Logging.

You can also validate headers with a headers schema (see Validating Requests), which is a tidy way to require an API key header on a route.

The raw request and streams

request.raw is the original Node IncomingMessage. You rarely need it, but it is the escape hatch for low-level work, for example reading a large upload as a stream instead of buffering it, or inspecting request.raw.socket. If you read the raw stream yourself, you must disable or skip Fastify's body parsing for that route (a custom content-type parser that returns the payload stream), otherwise the stream will already be consumed.

Request ids and logging together

Each request has a unique request.id, and request.log always includes it. A practical pattern is to return the id in error bodies so that when a user reports "it failed", you can search the logs for exactly that request. Server Options and Logging showed how to configure the header and generator.

Decorating the request

Need request.user after authentication? Declare it first with app.decorateRequest('user', null) and assign it in a hook. Declaring it keeps all request objects the same shape (faster) and gives plugins a clear contract. The decorators lesson has the details; chapter 7 builds authentication on top of it.

Common mistakes

  • Reading request.headers.Authorization (capital A). The key is authorization.
  • Expecting a body on GET. Use the query string for filters.
  • Forgetting that request.body is undefined when no body was sent. Use a body schema with required to enforce it.
  • Logging request.headers or request.body wholesale. You will leak tokens and personal data.
  • Mutating request.params or request.query and assuming later hooks see the original values.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you read the Content-Type header in a handler?

    Node lowercases header names, so use lowercase keys.
  2. 2. What does Fastify do with a request whose body is invalid JSON?

    The JSON parser fails and Fastify sends a 400 error without running the handler.
  3. 3. What is the difference between request.url and request.routeOptions.url?

    The pattern (for example /users/:id) is stable and good for metrics labels.
  4. 4. Which content types are parsed out of the box?

    Forms and uploads need @fastify/formbody and @fastify/multipart.

Summary

  • request bundles params, query, body, headers, method, url, id, ip, log, routeOptions and raw.
  • Header names are lowercase; params and query are strings unless a schema coerces them.
  • JSON and text bodies are parsed for you; invalid or empty JSON bodies produce a 400 before your handler.
  • Use routeOptions.url for stable metric labels.
  • Do not log whole headers or bodies; declare custom request properties with decorateRequest.

Next: The Reply Object