A browser request is only a method, a path, some headers and sometimes a body. This unit shows how an Express program turns such a request into decisions: which handler runs, how a JSON body becomes req.body, and which status code, headers and body make up the response. The code is a teaching example, not an installed or deployed service.
1. From request to handler
Definition 8.1.1
(Route and handler)
A route pairs an HTTP method and a path pattern with a handler, a function (req, res) or (req, res, next). Express compares each request with the registered routes and middleware in registration order. A handler that sends a response ends the search; a handler that calls next() passes the request to the next match.
Every HTTP request carries a method (such as GET, POST or PATCH) and a target (a path, optionally followed by a query string). Express compares each request against your routes in the order you registered them. A route matches only when both the method and the path pattern fit:
| Request | app.get('/items/:id') | app.patch('/items/:id') |
|---|---|---|
GET /items/1 | matches | no (wrong method) |
PATCH /items/1 | no (wrong method) | matches |
GET /items | no (path lacks the id segment) | no |
The method expresses what to do. The path identifies which resource.
2. Path parameters versus query strings
A path parameter can identify a specific resource. In /items/:id, the request /items/42 gives req.params.id === '42'. This single-segment :id parameter is a string, so a Map keyed by strings avoids number/string mismatches. Do not generalize this to every Express 5 parameter: wildcard parameters can contain arrays of path segments.
A query string refines or filters a collection: in /items?q=note, Express provides req.query.q. The query is not part of route matching, so /items and /items?q=note reach the same handler. A repeated key such as ?q=a&q=b can yield an array. Check typeof req.query.q === 'string' before using the value.
A useful rule: if removing the value would leave you pointing at a different resource, use the path. If it only narrows a list, use the query string.
Counterexample mode
Numeric keys never match path parameters
Claim: the store may use numbers as keys, because the request GET /items/1 selects item 1. Suppose the store is new Map([[1, { id: 1, name: 'Sample item' }]]) and the handler runs items.get(req.params.id). For GET /items/1, req.params.id is the string '1'. A Map compares keys with the same-value-zero rule, which does not equate '1' with 1, so items.get('1') returns undefined and the handler answers 404 although the item exists. Keep the keys as strings, as the full example does, or convert the parameter once and deliberately after checking that it is a canonical integer string.
3. JSON bodies, Content-Type and middleware order
A browser sends JSON in the request body and labels it with Content-Type: application/json. Express does not read bodies automatically. The express.json() middleware reads and parses the body, but only when the request's Content-Type matches its type option, which defaults to application/json.
Three cases need to be kept apart:
- Matching type, accepted JSON.
req.bodyholds the parsed value. The defaultstrict: truesetting accepts objects and arrays; the routes below apply stricter object and field validation afterwards. - Matching type, malformed or disallowed JSON. The parser skips ordinary route handlers and forwards an error: status
400, type'entity.parse.failed'. Even syntactically valid scalar JSON, such as42ornull, is rejected bystrict: true. - Non-matching or missing type. With no earlier body parser,
req.bodyremainsundefined. This is not a parse error. The POST and PATCH handlers below choose415 Unsupported Media Typeif they are reached and the type check fails.
Order matters. app.use(express.json()) must be registered before the routes that read req.body. Error-handling middleware takes four arguments (err, req, res, next) and is registered after the routes.
Common mistake
(Registering the fallback or the parser too early)
Registration order is matching order. A catch-all app.use((req, res) => res.status(404).json(...)) placed before the routes answers every request with 404, including GET /items/1, because it matches first and sends the response. A parser registered after the routes leaves req.body undefined in them. Register the parser first, then the routes, then the 404 fallback and finally the error middleware.
4. Validation, return and next
A request should receive at most one final response. A handler must either complete the response or pass control onwards. Writing return res.status(400).json(...) sends the response and stops that function, so its later statements cannot try to send a second response.
Calling next() does something different. It passes control to the next matching route or middleware. Calling next(err) skips ordinary middleware and goes to error handlers. Use return res... when you are answering. Use next(err) when another layer should answer.
Validate property existence safely. A check like body.name !== undefined misses the case where a property is present with the value undefined, and 'name' in body also finds inherited prototype properties. Object.hasOwn(body, 'name') and Object.keys(body) consider only the object's own properties. Also confirm that the body is a plain object first. JSON arrays parse successfully but are not valid input here.
Common mistake
(Truthiness is not validation)
A check such as if (!body.name) return res.status(400)... rejects a missing name and the empty string, but it accepts anything truthy. For the body {"name":42} or {"name":["a"]} the value is truthy, the check passes, and the later call body.name.trim() throws a TypeError because a number and an array have no trim method. Express then answers 500, a server fault, for what is really a client error. Test the type and the range explicitly, as isValidName does, so that such input receives 400.
5. Status, headers and body
A response has three parts:
- a status code, such as
200or404; - headers, such as
Content-TypeandLocation; - a body, here JSON.
res.status(code) sets the status. res.location(url) sets Location. res.json(value) serializes the value, sets Content-Type: application/json; charset=utf-8, and sends the response.
6. Complete illustrative example
This is an illustrative Express 5 CommonJS program, requiring Node.js 18 or later. It has not been installed or run for this chapter. The responses written in the route handlers are design choices for teaching; parser failures follow Express/body-parser behavior.
'use strict';
const express = require('express');
const app = express();
app.disable('x-powered-by');
app.set('etag', false);
// In-memory store: one process only, reset on every restart.
const items = new Map([['1', { id: '1', name: 'Sample item' }]]);
let nextId = 2; // classroom counter; assumed to stay within the safe integer range
function isPlainObject(value) {
return typeof value === 'object' && value !== null
&& Object.getPrototypeOf(value) === Object.prototype;
}
function isValidName(value) {
return typeof value === 'string'
&& value.trim().length > 0
&& value.trim().length <= 100;
}
app.use(express.json());
// GET collection, optional ?q= filter -> 200
app.get('/items', (req, res) => {
const q = typeof req.query.q === 'string' ? req.query.q.toLowerCase() : '';
const list = [...items.values()].filter((item) =>
item.name.toLowerCase().includes(q));
res.status(200).json(list);
});
// GET one -> 200 or 404
app.get('/items/:id', (req, res) => {
const item = items.get(req.params.id);
if (!item) {
return res.status(404).json({ error: 'Item not found' });
}
res.status(200).json(item);
});
// POST create -> 201, 400 or 415
app.post('/items', (req, res) => {
if (!req.is('application/json')) {
return res.status(415).json({ error: 'Content-Type must be application/json' });
}
const body = req.body;
if (!isPlainObject(body) || !Object.hasOwn(body, 'name') || !isValidName(body.name)) {
return res.status(400).json({ error: 'name must be a non-empty string (max 100)' });
}
const id = String(nextId++);
const item = { id, name: body.name.trim() };
items.set(id, item);
res.status(201).location(`/items/${id}`).json(item);
});
// PATCH update -> 200, 400, 404 or 415
app.patch('/items/:id', (req, res) => {
const item = items.get(req.params.id);
if (!item) {
return res.status(404).json({ error: 'Item not found' });
}
if (!req.is('application/json')) {
return res.status(415).json({ error: 'Content-Type must be application/json' });
}
const body = req.body;
if (!isPlainObject(body)) {
return res.status(400).json({ error: 'Body must be a JSON object' });
}
const keys = Object.keys(body);
if (keys.length !== 1 || keys[0] !== 'name') {
return res.status(400).json({ error: 'Only the name field may be updated' });
}
if (!isValidName(body.name)) {
return res.status(400).json({ error: 'name must be a non-empty string (max 100)' });
}
item.name = body.name.trim();
res.status(200).json(item);
});
// Unmatched method/path -> 404
app.use((req, res) => {
res.status(404).json({ error: 'Route not found' });
});
// Error middleware: malformed/disallowed JSON; other errors are delegated
app.use((err, req, res, next) => {
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'Invalid JSON body: expected an object or array' });
}
next(err);
});
app.listen(3000);
Some design notes on the example:
req.is()checks content type together with HTTP body framing; it does not validate JSON or the required fields. Do not infer the response from the absence of payload bytes alone. For example, a framed empty JSON body can reach field validation and receive400.- The global JSON parser runs before every route. A malformed JSON body therefore produces
400even forPATCH /items/99; the id check is never reached. Once parsing succeeds or is skipped, the PATCH handler checks existence first, so an unknown id receives404before its content checks. - Other parser errors are delegated: an oversized body receives
413, and an unsupported charset or content encoding receives415. Express's default handler uses an error's4xxor5xxstatus, otherwise500. Its body is not this application's JSON error format.
7. Worked examples
Worked example 8.1.2
(Create an item and read it back)
The following trace was constructed by hand, not captured from a running server. It sketches the client request and the expected response. The Date value varies, and Node.js connection headers (Connection, Keep-Alive) are omitted. The content lengths count UTF-8 payload bytes, excluding any display newline after the body.
POST /items HTTP/1.1
Host: localhost:3000
Content-Type: application/json
Content-Length: 19
{"name":"Notebook"}
HTTP/1.1 201 Created
Location: /items/2
Content-Type: application/json; charset=utf-8
Content-Length: 28
Date: <varies>
{"id":"2","name":"Notebook"}
Follow the request through the program. express.json() sees Content-Type: application/json, reads the 19 body bytes and sets req.body to { name: "Notebook" }. The router skips the two GET routes because the method differs and enters the POST /items handler. There req.is('application/json') is truthy, the body is a plain object with its own name property, and isValidName accepts the string. The handler takes id '2', increments nextId to 3, stores the item and answers 201 with a Location header and the JSON body. Reading the state back confirms the change: GET /items/2 returns 200 with the same object, and GET /items?q=note returns an array holding only that item, because 'sample item' does not contain note while 'notebook' does.
Worked example 8.1.3
(Which layer answers each request)
Summary of outcomes, assuming the illustrated POST has created item 2. Except where stated, requests with a body use Content-Type: application/json and ordinary UTF-8 encoding within the parser's size limit:
| Request | Result |
|---|---|
GET /items/1 | 200 with the sample item |
GET /items/99 | 404 {"error":"Item not found"} |
POST /items with body {"name":" "} | 400 |
POST /items with body {"name": | 400 with the JSON parser error message above |
POST /items with body 42 | 400 because strict JSON parsing rejects scalars |
POST /items with Content-Type: text/plain | 415 |
PATCH /items/2 with body {"name":"Diary"} | 200 |
PATCH /items/2 with body {"color":"red"} | 400 |
PATCH /items/99 | 404 |
PATCH /items/99 with malformed JSON | 400 before the id check |
Group the rows by the layer that produces the answer. The error middleware answers the two bodies the parser rejects before any route runs: the truncated {"name": and the scalar 42, which strict refuses. Route handlers answer the rest: 404 for an unknown id, 415 when req.is fails, and 400 for validation failures such as a blank name or an unexpected field. For PATCH /items/99 the id check precedes the body checks, so a well-formed body still gives 404, while malformed JSON never reaches the handler and gives 400. The table therefore records an ordering of checks as well as a list of status codes.
Worked example 8.1.4
(Registering the parser too late)
Suppose the two registration lines of the program are swapped so that the route comes first.
// Faulty order: the routes are registered before the parser.
app.post('/items', createItem); // the same handler as in the full example
app.use(express.json());
The client sends the same successful request as in the first example: POST /items with Content-Type: application/json and the body {"name":"Notebook"}. The router reaches the POST /items handler before the parser has run, so req.body is still undefined. The handler's req.is('application/json') test passes because it inspects only the request headers (type and body framing), not req.body, so there is no 415. Then isPlainObject(undefined) is false and the handler answers 400 {"error":"name must be a non-empty string (max 100)"}. The same input now fails, and the message blames the input although the fault is the registration order. A malformed body would also receive this generic 400 instead of the parser's error response. The repair is to register app.use(express.json()) before every route that reads req.body.
8. The client side: Promises, response.ok and the DOM
fetch returns a Promise in the browser. It resolves when response headers arrive, even for 404 or 500. Request failures, including network errors, invalid requests and cancellation, can reject it. Check response.ok, which is true for statuses 200–299, before treating the response as a success.
async function createItem(name) {
const response = await fetch('/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name }),
});
if (!response.ok) {
throw new Error(`Create failed with status ${response.status}`);
}
return response.json(); // another Promise: the parsed body
}
response.json() reads and parses the body asynchronously and can itself reject, for example if the server returns invalid JSON. The caller of createItem must handle failures from both stages.
The server's Map and the page's DOM are separate states in separate programs. A successful POST changes the Map, but the page changes only when client code updates the DOM afterwards. Editing the DOM by itself does not change the server; an event handler would need to send another request.
Two requests need not complete in the order the browser started them. Updating the DOM from every response without checking which operation is still current can display stale data. In this example, each server mutation is synchronous, but competing PATCH requests still overwrite the same name in server processing order. There is no version check, and retrying a POST can create a second item. Reliable conflict handling and retry deduplication need an explicit design.
Restarting the Node process recreates the Map with the single sample item and resets nextId to 2. Running two processes gives two independent Maps. Durable shared storage, commonly a database, and appropriate concurrency control are needed to preserve and coordinate this state across processes.
9. Practice
Quick check
(Which handler answers?)
With the full example, state the response for (a) DELETE /items/1, (b) POST /items/1, (c) GET /items?q=a&q=b.
Solution
(a) No route registers DELETE, so the request falls through to the final handler: 404 {"error":"Route not found"}. (b) POST is registered only for /items, so POST /items/1 also reaches the final handler and gets the same 404. A stricter API might answer 405 Method Not Allowed with an Allow header, but this program does not. (c) The route GET /items matches. req.query.q is an array, so typeof req.query.q === 'string' is false, q becomes the empty string and every item is returned with 200.
Quick check
(Choose the status code)
For POST /items, give the status code and the layer that produces it: (a) JSON body {"name":42}; (b) JSON body {"name":; (c) Content-Type: text/plain with body hello.
Solution
(a) 400 from the route handler: the body parses, but isValidName rejects a number. (b) 400 from the error middleware: the parser fails with entity.parse.failed and the handler never runs. (c) 415 from the route handler: express.json() skips a non-matching type and leaves req.body undefined, then req.is('application/json') fails.
Quick check
(The double response)
Find the defect: app.get('/items/:id', (req, res) => { const item = items.get(req.params.id); if (!item) res.status(404).json({ error: 'Item not found' }); res.status(200).json(item); });
Solution
The 404 branch has no return, so execution continues to the second res.status(200).json(item). The client already received the 404, and the second attempt tries to set headers on a response that has been sent, which makes Node throw ERR_HTTP_HEADERS_SENT. The fix is return res.status(404).json({ error: 'Item not found' });, which sends the response and stops the function.
Quick check
(A 400 for valid input)
After a refactor, POST /items with Content-Type: application/json and body {"name":"Diary"} returns 400, although the handler code is unchanged. What is the most likely cause, and how can you confirm it?
Solution
The most likely cause is that app.use(express.json()) now comes after the route, or has been removed, so req.body is undefined when the handler runs. isPlainObject(undefined) is false, which gives the 400. To confirm, log req.body at the top of the handler or compare the order of the app.use and route registrations; the fix is to register the parser first.
Quick check
(Reading a 404 in the browser)
The browser runs const response = await fetch('/items/99');. What does the Promise do, what are response.ok and response.status, and what must the code check before calling response.json()?
Solution
The Promise fulfills, because headers arrived; HTTP failure statuses do not reject it. response.status is 404 and response.ok is false. The code should test response.ok before treating the body as an item. The body here is {"error":"Item not found"}, which response.json() would parse without error, so skipping the check would silently treat an error object as data.