skip to content

Request & Response

The request exposes params, a read-only query and a body left undefined until a parser runs; the response sets status, sends JSON, redirects or renders. Interviewers probe what changed in Express 5.

on this pageshow

questions

5

In an Express 5 route handler, where do req.params, req.query and req.body get their values, and why can req.body be undefined?

level: juniorimportance: must knowfreq 72%

answer

  1. three sources: path, URL, payload
  2. route pattern versus query string
  3. body needs a parser middleware
  4. Express 4 gave an empty object

basics

~10 s

req.params holds the named route parameters, req.query the parsed query string, and req.body the payload. In Express 5 req.body stays undefined until a parser such as express.json() runs and the request's Content-Type matches it.

solid answer

~40 s

`req.params` is filled from the matched route path, so `/orders/:id` gives `req.params.id` as a decoded string. `req.query` is a getter that parses the URL's query string with the `'query parser'` setting, so its values are strings, or arrays when a key repeats. `req.body` is not filled by Express itself: a body-parsing middleware such as `express.json()` or `express.urlencoded()` reads the stream and sets it. In Express 5 it is `undefined` until that happens, so it stays `undefined` when no parser is mounted, the parser is registered after the route, the `Content-Type` does not match the parser's `type`, or there was no body. Express 4 defaulted it to `{}`, which hid the missing parser; in Express 5 `req.body.name` throws a `TypeError` instead.

code

javascript · 17 lines
javascript
const express = require('express');
const app = express();

app.use(express.json());                          // application/json -> req.body
app.use(express.urlencoded({ extended: false })); // HTML form posts -> req.body

// POST /orders/42/notes?notify=email
app.post('/orders/:id/notes', (req, res) => {
  const { id } = req.params;    // '42', always a string
  const { notify } = req.query; // 'email', an array, or undefined
  if (req.body === undefined) {
    return res.status(400).json({ error: 'expected a JSON or form body' });
  }
  res.status(201).json({ orderId: id, notify, note: req.body.text });
});

app.listen(3000);

go deeper

for a junior

Recall the three sources: route path for req.params, query string for req.query, a parser middleware for req.body, and that values from the URL are strings.

for a middle

Explain why req.body is undefined: no parser, parser registered after the route, or a Content-Type the parser's type option skips; mention the null-prototype req.params.

for a senior

Treat the Express 5 undefined body as a wiring alarm, validate all three inputs as untrusted, and catch upgrades where code relied on Express 4's empty-object default.

for a principal

Decide where parsers are mounted across services and whether handlers validate whole inputs with a schema, so a missing parser or odd query shape fails loudly everywhere.

## Three properties, three sources An Express handler receives `req`, which extends Node's incoming message with helpers. Three of those helpers carry the client's input, and each one is filled at a different moment by a different piece of code: | Property | Filled from | Filled by | Typical values | |---|---|---|---| | `req.params` | the matched route path | the router, when the route matches | decoded strings | | `req.query` | the URL's query string | a getter, on every read | strings, or arrays for repeated keys | | `req.body` | the request payload | a body-parsing middleware | whatever that parser produces | Knowing which code fills each property tells you why one of them can be missing when the others are not. ## `req.params`: the route pattern When a request matches `app.post('/orders/:id/notes', ...)`, the router copies each named segment into `req.params`. A few Express 5 details matter in practice: - **Values are strings**, decoded with `decodeURIComponent`. `/orders/42` gives `'42'`, not the number 42. - **The object has a null prototype** for string paths, so `req.params.hasOwnProperty('id')` throws because the method does not exist. Use `Object.hasOwn(req.params, 'id')` or a plain `in` check. - **Wildcard parameters are arrays** of path segments, and optional parameters the URL did not supply are left out entirely rather than set to `undefined`. How the path pattern itself is written belongs to the routing material; here the point is only what lands in the object. ## `req.query`: a getter over the URL `req.query` is not a stored object. It is a **getter** that parses the query string each time you read it, using the parser named by the `'query parser'` application setting. Express 5 defaults that setting to `'simple'`, which uses Node's own query-string parser: - `?status=open` gives `{ status: 'open' }`. - `?tag=a&tag=b` gives `{ tag: ['a', 'b'] }`, so a value you expected to be a string can be an array. - With no query string at all you get an empty object, never `undefined`. Because the values come from the URL, they are always text and always untrusted: validate before using them. ## `req.body`: only after a parser runs Express does not read the request stream on its own. A body-parsing middleware does, and only for requests whose `Content-Type` matches the parser's `type` option: 1. `express.json()` parses `application/json` into an object or array. 2. `express.urlencoded()` parses HTML form posts (`application/x-www-form-urlencoded`). 3. `express.text()` and `express.raw()` give a string or a `Buffer`. In **Express 5, `req.body` is `undefined` until one of them sets it.** The documentation for the parsers lists the cases where it stays `undefined`: there was no body to parse, the `Content-Type` did not match, or an error occurred. Add the two wiring mistakes: - **No parser mounted.** The handler sees `undefined` for every request. - **Parser registered after the route.** Express runs middleware in registration order, so a parser added with `app.use` below the route has not run when the handler reads `req.body`. - **Client sends the wrong header.** A JSON payload sent as `text/plain` is skipped by `express.json()`, which leaves `req.body` untouched rather than failing. Multipart forms are not handled by any of the built-in parsers; they need a dedicated multipart middleware. ## What changed from Express 4 Express 4 initialised `req.body` to `{}`. A missing parser therefore produced a handler that silently saw empty input, and `req.body.name` quietly evaluated to `undefined`. In Express 5 the same line throws `TypeError: Cannot read properties of undefined (reading 'name')`. Express catches a synchronous throw inside a handler and forwards it to error-handling middleware, so the client gets a 500 instead of a misleading success. The loud failure is the point: it surfaces the wiring mistake on the first request. A defensive handler checks `req.body === undefined` (or validates the whole body with a schema) before reading fields, and the parser is mounted near the top of the app, before the routes that need it. ## Reading all three safely The three properties share one trait: every value in them came from the client. A few habits follow from that: - **Convert explicitly.** `Number(req.params.id)` or a schema's coercion, then reject `NaN`, rather than comparing a string with a number. - **Expect shape surprises.** `req.query.tag` may be a string, an array or missing; `req.body.items` may not be an array at all. The Express documentation warns that even `req.body.foo.toString()` can fail, because `foo` may be absent or not a string. - **Do not merge sources blindly.** Express 5 removed `req.param(name)`, which looked a name up across params, body and query; read each value from the property that should carry it. - **Keep parsers before routes.** A quick test that posts a body and asserts the handler saw it catches a parser registered too late.

  • A client posts valid JSON with Content-Type: text/plain to a route behind express.json(). What does the handler see?
    `express.json()` only parses requests whose `Content-Type` matches its `type` option, `application/json` by default. A `text/plain` request is skipped without an error, so `req.body` stays `undefined` in Express 5. Either the client fixes its header or the parser's `type` is widened deliberately, for example to an array of accepted media types.
  • Why does req.params.hasOwnProperty('id') throw in Express 5?
    For string route paths Express 5 builds `req.params` with a null prototype, so it inherits nothing from `Object.prototype` and `hasOwnProperty` is not a function on it. Use `Object.hasOwn(req.params, 'id')` or an `in` check. A route defined with a regular expression still gets an ordinary object.

  • Express parses JSON request bodies automatically without any middleware
  • req.body is an empty object when no parser is mounted
  • req.params.id is converted to a number when it looks numeric
  • req.query values are always single strings, never arrays
  • Mounting express.json() after the routes still parses their bodies

Assumes Express 5, where req.body is undefined until a parser sets it and req.params has a null prototype; Express 4 defaulted req.body to {}.

open as a page

In Express 5, how do res.format, res.redirect and res.render let one route answer browsers with HTML and API clients with JSON?

level: middleimportance: should knowfreq 30%

basics

~20 s

res.format picks a callback by the Accept header, so an html branch can redirect or render while a json branch calls res.json. res.redirect defaults to 302 and takes a status first; res.render needs a view engine and sends 200 HTML.

open as a page

In Express 5, what do the limit, type, strict and verify options of express.json control, and how does each one fail a request?

level: middleimportance: should knowfreq 48%

basics

~20 s

limit caps body size (100kb default, 413 when exceeded), type picks which Content-Type is parsed (others are skipped), strict accepts only objects and arrays (else 400), and verify inspects the raw Buffer, failing with 403 when it throws.

open as a page

After an Express 4 to 5 upgrade, a search route's ?filter[status]=open stops filtering and middleware that rewrote req.query breaks; what changed?

level: seniorimportance: should knowfreq 40%

basics

~10 s

Express 5 changed the default 'query parser' from 'extended' to 'simple', which keeps filter[status] as a flat key, and made req.query a getter that re-parses the URL, so assignments to it throw or vanish.

open as a page

After upgrading to Express 5, handlers calling res.send(404), res.json(user, 201) and res.redirect('/login', 301) misbehave; what does each now do, and what replaces it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

In Express 5 res.send(404) answers 200 with the JSON body 404, res.json(user, 201) answers 200 because the status argument is ignored, and res.redirect('/login', 301) throws a TypeError, giving a 500. Use res.sendStatus, res.status(code).json and res.redirect(status, url).

open as a page