Loading

T9 APIs · Lesson 4

Middleware

Middleware are the checkpoints between a request's arrival and its route: functions that log it, check it, read its body or answer it early, each passing the request on with next. Write your own, place them in the right order, use Express's own for JSON, forms and files, and end the chain with a 404 and an error handler.

  • say what middleware is, add it with app.use, and pass a request on with next
  • log every request and its answer, and put middleware on one route or one path
  • answer early from a guard, and pass data along on req and res.locals
  • read JSON, form and text bodies with Express's parsers
  • serve a folder of files with express.static
  • end the chain with a 404 of your own and an error handler with four parameters
About 65 minutesChecked against Node.js on the laptop (the kit runs every code block with it) 22.23.1 (2026-11-15); GNU Bash on the laptop (the kit compares every shell block with it, in a sandbox) 5.3.9 (2026-11-15); Express, from npm (the kit compares every Express block with it, in its sandbox; the page runs the small Express of plan 25) 5.3.0 (2026-11-15)Play this lesson's games

The back cover

An airport has checkpoints between the door and the gate. One checks the ticket, one weighs the bag, one stamps the passport, and each either waves the traveller on or stops them there. The gate never sees a traveller who failed a check.

These pages show such checkpoints in Express, called middleware. They write a middleware of their own and a logger that sees every answer. They add guards that stop a request early, readers that turn a body into data, and a folder of files served as it stands. Two checkpoints at the end of the line answer what nothing else did.

Before you start

The story: Parcels that should never reach a bench

Yesterday a parcel with no seal on it reached the ledger bench, and the clerk wrote its numbers into the yard's books before anyone noticed. Another came in soaking wet, its label running, and the gauge bench spent an hour guessing what it held.

Nobody had kept a list of what came through the gate, so nobody could say when either one arrived.

Yardmaster Waybill walks the length of the belt. "A bench should only sort," she says. "Put checkpoints along the belt before the benches. One writes every parcel into the log. One opens the wrapping and lays the contents flat. One turns back a parcel with no seal. Each does its one job, then passes the parcel on, or sends it back."

In lesson 03 every request went straight to its route. Real APIs do work before the route: they write each request into a log, check a key, read the body, or turn a request away. Doing that inside every route would mean the same lines thirty times over.

Express does it once, in middleware: functions that stand between a request's arrival and its route. Each one sees the request, does its one job, then passes the request on, or answers it there and then.

It builds on these ideas. Each one has a tiny example, so you can check that you remember it.

What you already knowA tiny exampleWhere it comes back
Routes and handlers.app.get("/", (req, res) => ...)Middleware is a handler too.
next and next("route").next()Passing a request on.
Routers and mounts.app.use("/gauges", router)Middleware on one path.
Status codes.401, 404, 500Early answers and errors.
Headers.req.get("x-key")Checking a key.
JSON and Content-Type.application/jsonReading a JSON body.
Events.res.on("finish", ...)Logging the answer.
throw and errors.throw new Error("...")The error handler.
async and await.async (req, res) => ...Errors after an await.
Files and folders.public/index.htmlServing files.

By the end of this lesson you will be able to:

  • say what middleware is, add it with app.use, and pass a request on with next;
  • log every request and its answer, and put middleware on one route or one path;
  • answer early from a guard, and pass data along on req and res.locals;
  • read JSON, form and text bodies with Express's parsers;
  • serve a folder of files with express.static;
  • end the chain with a 404 of your own and an error handler with four parameters.

How to follow this lesson

Every block is an Express app and its own client, as in lesson 03. It runs on the page in the small Node with its small Express, and it has also been run with the real Express 5.3.0 in real Node 22, where it prints the same.

Some lines come from the server and some from the client. The server's lines are printed while it handles a request, so they come before the client's line about the same request.

In one line

Middleware are functions that stand between a request's arrival and its route: each does one job, then passes the request on with next, or answers it.

What middleware is

At a glance

Between a request's arrival and its route stand checkpoints. Each one looks at the request and either lets it pass or answers it.

A middleware is a function of three parameters, req, res and next, that does one job. Then it calls next() to pass the request on, or it answers the request itself. The call app.use adds one for every request, or for every request under one path. Express runs its functions in the order they were written, so middleware goes above the routes that it serves.

Take a guess: Did Express invent the word middleware for its checkpoints?

A middleware is a function with three parameters: the request, the response and next. It is the same shape as a route's handler, with one difference in use: it usually does not answer. It does its job and calls next(), which hands the request to the next function in line.

app.use(fn) adds a middleware for every request, whatever its verb and path. Here is the smallest one, a checkpoint that prints each request as it arrives:

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  console.log("checkpoint:", req.method, req.url);
  next();
});
app.get("/gauges", (req, res) => res.send("the gauges"));
const server = app.listen(3000, async () => {
  for (const path of ["/gauges", "/nowhere"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log("client:", path, r.status);
  }
  server.close();
});

Terminal: node app.js

checkpoint: GET /gauges
client: /gauges 200
checkpoint: GET /nowhere
client: /nowhere 404

Read the lines in pairs. For each request, the server printed its checkpoint line first, while it was handling the request; then the client printed the answer it got. The checkpoint ran for /nowhere too, because app.use catches every request. It called next(), the line went on, no route matched, and Express answered 404.

A line of functions, in the order written

An app keeps one line of functions: middleware and routes, in the order you wrote them. A request walks down the line. Each function it meets either answers, which ends the walk, or calls next, which moves it one step further. Three middleware and two routes show the walk:

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => { console.log("1. every request:", req.method, req.url); next(); });
app.use("/admin", (req, res, next) => { console.log("2. admin only:", req.baseUrl, req.url); next(); });
app.use((req, res, next) => { req.hall = "engine"; res.locals.started = true; next(); });
app.get("/admin/gauges", (req, res) => res.json({ hall: req.hall, started: res.locals.started }));
app.get("/", (req, res) => res.send("front"));
const server = app.listen(3000, async () => {
  for (const p of ["/", "/admin/gauges", "/nowhere"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, ""));
  }
  server.close();
});

Terminal: node app.js

1. every request: GET /
/ 200 front
1. every request: GET /admin/gauges
2. admin only: /admin /gauges
/admin/gauges 200 {"hall":"engine","started":true}
1. every request: GET /nowhere
/nowhere 404 Cannot GET /nowhere

The first middleware ran for all three requests. The second was added with a path, app.use("/admin", fn), so it ran only for paths that start with /admin; inside it, req.baseUrl was /admin and req.url the rest, as in a router. The third ran for every request and added a field to req and one to res.locals, an object Express gives each response for exactly this.

The route for /admin/gauges then read both fields. Nothing stops middleware from adding to req, but res.locals is the place Express sets aside, and it starts empty for every request.

Added withRuns forInside it
app.use(fn)every request, any verb, any pathreq.url is the whole path
app.use("/admin", fn)paths that start with /adminreq.baseUrl is /admin; req.url is the rest
app.get("/x", fn, handler)GET /x onlya step before that route's handler

A path in app.use matches whole segments: /admin matches /admin and /admin/gauges, but not /administer.

Worked example 1

Number every request: a middleware that counts them and puts the count in a header, X-Request-Number, on every answer, found or not.

What we have: an app with one route, and a count kept outside the functions so that it lasts between requests

What we need: the header on every answer, the 404 included, with the numbers 1, 2 and 3

The plan: a variable for the count; a middleware added first with app.use, which adds one, sets the header with res.set and calls next

app.js

const express = require("express");
const app = express();
let count = 0;
app.use((req, res, next) => {
  count += 1;
  res.set("X-Request-Number", String(count));
  next();
});
app.get("/gauges", (req, res) => res.json({ boiler: 95 }));
const server = app.listen(3000, async () => {
  for (const path of ["/gauges", "/gauges", "/nowhere"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, r.status, r.headers.get("x-request-number"));
  }
  server.close();
});

Terminal: node app.js

/gauges 200 1
/gauges 200 2
/nowhere 404 3
  1. The count lives outside the middleware, so it is not reset for each request.
  2. res.set puts the header on the response early; whatever answers later keeps it.
  3. The 404 for /nowhere came from Express, and it still carried the header, because the middleware ran first and Express's 404 page keeps the headers already set.

The three answers carry 1, 2 and 3 in X-Request-Number, the 404 included.

Check: Three requests, three numbers in order; the middleware ran before every answer.

Another way: put the number on req as well, req.number = count, so that a route or a log can print it.

A path that fails: adding the middleware after the routes. A route answers and never calls next, so a middleware below it never runs for that path, and the header would be missing.

When you are stuck: A middleware never runs, or the request never ends

Is it above the routes? Functions run in the order written, and a route that answers ends the walk.

Does it call next() on every path through it? A middleware that neither answers nor calls next leaves the request waiting for ever, and the client waits with it.

Does its path match? app.use("/admin", fn) runs only for paths that start with /admin.

Your turn

Which two things can a middleware do with a request, so that the request does not wait for ever?Tap to reveal
  1. One ends the walk; the other moves it on.

Answer it, or call next().

A middleware added with app.use("/admin", fn) gets a request for /admin/ledger. What are req.baseUrl and req.url inside it?Tap to reveal
  1. It behaves like a router mounted at that path.

req.baseUrl is /admin and req.url is /ledger.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.use((req, res, next) => { res.locals.who = "the gate"; next(); });
app.get("/", (req, res) => res.send("passed " + res.locals.who));
const server = app.listen(3000, async () => {
  console.log(await (await fetch("http://localhost:3000/")).text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
passed the gate
  1. The middleware runs first and puts who on res.locals.
  2. The route reads it from the same res.locals.

It prints passed the gate.

Did you know?

Middleware from Connect

Express's middleware has a parent. Connect, in its own words an extensible HTTP server framework for Node, called its plugins middleware, and earlier versions of Express were built on it. Express 4 cut the tie: its migration guide says that it no longer depends on Connect, and that it removed all built-in middleware from its core, except express.static.

Why it fits here: It answers this topic's question: the name and the idea came to Express from Connect, which Express 4 left behind.

Sources: Connect on GitHub; Express: Moving to Express 4

Koa, from the same team

Express's own team built a second framework. Koa's site says that it was designed by the team behind Express, to be a smaller, more expressive and more robust foundation for web applications and APIs. Its middleware are async functions that cascade: when there is nothing left to run downstream, the stack unwinds, and each middleware resumes for its upstream work.

Why it fits here: It shows another shape of this topic's line: Koa's middleware, from Express's own team, run down the line and back up.

Source: Koa

In one line

A middleware is a function of req, res and next that does one job and calls next(), or answers. It is added with app.use for every request or for one path, and functions run in the order written, so middleware goes above the routes.

A logger, and middleware on one route

At a glance

A logger writes one line for every request: what was asked, and what was answered.

The first half is easy, as a middleware sees the request. The answer comes later, from a route the logger cannot see. So the logger listens for the response's finish event, which comes when the last byte has been handed over, and then it knows the final status. It calls next at once, so the request goes on. A middleware can also guard one route only, listed before that route's handler.

Take a guess: Why do so many servers write their log lines in the same shape?

A logger writes one line for every request: what was asked, and what was answered. The first half is easy, because a middleware sees the request. The second half is harder, because the answer comes later, from a route the logger cannot see.

The response is an event emitter, as in the Node track. When the last byte of the answer has been handed over, it emits "finish". A logger listens for that event, then calls next and lets the request go on:

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  res.on("finish", () => console.log("log:", req.method, req.originalUrl, res.statusCode));
  next();
});
app.get("/a", (req, res) => res.send("a"));
const server = app.listen(3000, async () => {
  for (const p of ["/a", "/b"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log("client:", p, r.status);
  }
  server.close();
});

Terminal: node app.js

log: GET /a 200
client: /a 200
log: GET /b 404
client: /b 404

The listener ran after the answer was sent, so res.statusCode held the final status: 200 for /a, and 404 for /b, which Express answered itself. The logger used req.originalUrl, the whole path, which stays the same even inside a mounted router.

This is how real loggers work. The popular package morgan, for one, is a middleware that waits for the answer in the same way and writes one line per request.

Middleware on one route

A route can take several functions, as lesson 03 showed with next. A middleware written once can be put in front of the routes that need it, and only those. Here a small function makes stamps, and each route chooses its own:

app.js

const express = require("express");
const app = express();
const stamp = (label) => (req, res, next) => {
  res.append("X-Stamps", label);
  next();
};
app.get("/parcel", stamp("weighed"), stamp("opened"), (req, res) => res.send("sorted"));
app.get("/letter", stamp("weighed"), (req, res) => res.send("delivered"));
const server = app.listen(3000, async () => {
  for (const path of ["/parcel", "/letter"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, r.headers.get("x-stamps"), await r.text());
  }
  server.close();
});

Terminal: node app.js

/parcel weighed, opened sorted
/letter weighed delivered

stamp(label) returns a middleware, so stamp("weighed") and stamp("opened") are two different checkpoints made by one function. res.append adds a value to a header instead of replacing it, and the client read both values joined by a comma and a space. The parcel went through two stamps; the letter through one.

Where the middleware is putIt runs for
app.use(fn)every request
app.use("/path", fn)every request whose path starts with /path
app.get("/path", fn, handler)GET /path only, before its handler
router.use(fn)every request that reaches the router

Worked example 2

Write a logger that prints, for each request, the verb, the whole path, the status and the size of the answer in bytes.

What we have: two routes, one of them answering 404 in JSON, and a client that reads three answers

What we need: one line per request, written after the answer, with the Content-Length that went out

The plan: a middleware at the top that listens for finish; inside the listener read res.statusCode and res.get("Content-Length"); call next at once

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  res.on("finish", () => console.log(`${req.method} ${req.originalUrl} answered ${res.statusCode} with ${res.get("Content-Length")} bytes`));
  next();
});
app.get("/gauges", (req, res) => res.json({ boiler: 95 }));
app.get("/gauges/:name", (req, res) => res.status(404).json({ error: "no such gauge" }));
const server = app.listen(3000, async () => {
  for (const path of ["/gauges", "/gauges/fan", "/nowhere"]) {
    await (await fetch("http://localhost:3000" + path)).text();
  }
  server.close();
});

Terminal: node app.js

GET /gauges answered 200 with 13 bytes
GET /gauges/fan answered 404 with 25 bytes
GET /nowhere answered 404 with 146 bytes
  1. {"boiler":95} is 13 bytes and {"error":"no such gauge"} is 25; Express set Content-Length for both.
  2. The third request found no route; Express's 404 page is 146 bytes, and the logger saw that too.
  3. The client only reads the answers, so every printed line is the logger's.

The three lines read 200 with 13 bytes, 404 with 25 bytes and 404 with 146 bytes.

Check: Each line was written after its answer, and the sizes are the lengths of the bodies that were sent.

Another way: time each request: keep performance.now() when the request arrives and print the difference in the finish listener. The times change from run to run, which is why this page does not print them.

A path that fails: printing res.statusCode in the middleware itself, before next. At that moment no route has answered, so it prints 200 for every request, the 404s included.

When you are stuck: The logger prints the wrong status, or prints nothing

Is the status read inside the finish listener? Before the answer, res.statusCode is still 200.

Does the logger call next()? Without it, every request stops at the logger.

Is the logger the first middleware? A route above it answers before the logger ever sees the request.

Your turn

Which event of the response tells a logger that the answer has gone?Tap to reveal
  1. Its name says the work is done.

"finish", listened for with res.on("finish", ...).

How do you put a middleware in front of one route only?Tap to reveal
  1. A route takes several functions.

List it before the handler: app.get("/path", middleware, handler).

cat > app.js <<'END'
const express = require("express");
const app = express();
const tag = (t) => (req, res, next) => { res.append("X-Tag", t); next(); };
app.get("/", tag("a"), tag("b"), tag("c"), (req, res) => res.send("ok"));
const server = app.listen(3000, async () => {
  console.log((await fetch("http://localhost:3000/")).headers.get("x-tag"));
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
a, b, c
  1. Each tag middleware appends its value to the same header.
  2. The client reads all the values of one header joined by a comma and a space.

It prints a, b, c.

Did you know?

One log line for every server

Many web servers write their log lines in one shape. The documentation of W3C httpd says that every server used to have its own logfile format, which made general statistics collectors hard to write. So it brought in a common logfile format: remotehost rfc931 authuser [date] "request" status bytes. The logger morgan still writes it, as Standard Apache common log output.

Why it fits here: It answers this topic's question: servers share the common logfile format, made so that one tool could read every log.

Sources: W3C httpd: Logging Control; morgan on GitHub

A logger named after Dexter

The logger kept by the Express project has a curious name. The README of morgan, an HTTP request logger middleware for Node, says that it is named after Dexter, a show you should not watch until completion. Like the logger of this topic, it waits for the answer, then writes one line per request.

Why it fits here: It adds to this topic's logger: morgan, the logger kept by the Express project, is named after the TV show Dexter.

Source: morgan on GitHub

In one line

A logger listens for the response's finish event, so it sees the final status, and calls next at once. A middleware can also stand in front of one route only, listed before its handler.

Guards, and passing data along

At a glance

Some checkpoints turn requests away. A guard checks something, such as a key, before the route runs.

When the check fails, the guard answers at once, such as 401 Unauthorized for a missing key, with return in front so that nothing runs after. When the check passes, it calls next. A middleware can also pass what it learns to the route, such as who is asking, on req or on res.locals. Both last for one request only, and the next request starts clean.

Take a guess: What must every 401 answer carry, by the standard?

A middleware does not have to call next. A guard is a middleware that checks something and answers at once when the check fails, so the request never reaches the route. The status for a missing or wrong key is 401 Unauthorized, which means: say who you are first.

app.js

const express = require("express");
const app = express();
app.use("/admin", (req, res, next) => {
  if (req.get("x-key") !== "brass") return res.status(401).json({ error: "a key is needed" });
  next();
});
app.get("/admin/ledger", (req, res) => res.json({ ok: true }));
const server = app.listen(3000, async () => {
  for (const key of [undefined, "tin", "brass"]) {
    const r = await fetch("http://localhost:3000/admin/ledger", { headers: key ? { "X-Key": key } : {} });
    console.log(key, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

undefined 401 {"error":"a key is needed"}
tin 401 {"error":"a key is needed"}
brass 200 {"ok":true}

The guard sits on /admin, so it checks every request below it. Without a key, and with the wrong one, it answered 401 and returned; the route never ran. With the right key it called next, and the ledger answered.

Look at the return in front of the answer. It ends the guard at its answer, so the next line, next(), never runs. Without it the guard would answer and pass the request on, and the route would try to answer a second time.

A key in a header is not real security

A fixed key such as brass shows the shape of a guard and nothing more. Real APIs check a token that the server itself issued, signed so that nobody can forge it; that is the track on authentication. The guard's place in the line stays the same.

Passing data along

Middleware often works something out that a route needs later: who sent the request, when it arrived, which hall it is for. It puts the result on the request or on res.locals, and the route reads it there:

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  req.courier = req.get("x-courier") ?? "unknown";
  res.locals.receivedAt = "gate 3";
  next();
});
app.get("/parcels", (req, res) => res.json({ courier: req.courier, where: res.locals.receivedAt }));
const server = app.listen(3000, async () => {
  for (const name of ["Ravi", undefined]) {
    const r = await fetch("http://localhost:3000/parcels", { headers: name ? { "X-Courier": name } : {} });
    console.log(await r.text());
  }
  server.close();
});

Terminal: node app.js

{"courier":"Ravi","where":"gate 3"}
{"courier":"unknown","where":"gate 3"}

The middleware read a header, X-Courier, and kept its value on req, with a fallback when it was missing. It also put a value on res.locals. The route used both. A new req and a new res.locals are made for every request, so nothing leaks from one request to the next.

Where to keep itGood forLasts for
req.somethingfacts about the request: who sent it, what it asksone request
res.locals.somethingvalues for the answer, set by Express's own conventionone request
app.locals.somethingsettings for the whole app, such as its namethe life of the app

Worked example 3

Open the gauges for reading to everyone, but let only a request with the key change them: a guard on the delete route only.

What we have: one gauge, a GET route for the list and a DELETE route for one gauge

What we need: GET works without a key; DELETE without the key gets 401 and changes nothing; DELETE with the key answers 204 and removes the gauge

The plan: write the guard as a named function, needKey; list it before the DELETE route's handler and nowhere else

app.js

const express = require("express");
const app = express();
const gauges = { boiler: 95 };
const needKey = (req, res, next) => {
  if (req.get("x-key") !== "brass") return res.status(401).json({ error: "a key is needed to change the gauges" });
  next();
};
app.get("/gauges", (req, res) => res.json(gauges));
app.delete("/gauges/:name", needKey, (req, res) => {
  delete gauges[req.params.name];
  res.status(204).end();
});
const server = app.listen(3000, async () => {
  const asks = [["GET", {}], ["DELETE", {}], ["DELETE", { "X-Key": "brass" }], ["GET", {}]];
  for (const [method, headers] of asks) {
    const path = method === "GET" ? "/gauges" : "/gauges/boiler";
    const r = await fetch("http://localhost:3000" + path, { method, headers });
    console.log(method, path, r.status, (await r.text()) || "(no body)");
  }
  server.close();
});

Terminal: node app.js

GET /gauges 200 {"boiler":95}
DELETE /gauges/boiler 401 {"error":"a key is needed to change the gauges"}
DELETE /gauges/boiler 204 (no body)
GET /gauges 200 {}
  1. The first GET needs no key and lists the boiler.
  2. The DELETE without a key stopped at needKey with 401; the gauge stayed.
  3. The DELETE with the key passed needKey, and the handler removed the gauge and answered 204, which has no body.
  4. The last GET shows the empty list: the delete took effect only once.

Reading is open (200), a delete without the key is refused (401), and with the key it works (204).

Check: The list before and after shows that only the delete with the key changed anything.

Another way: put needKey on a router that holds every route that writes, and mount it with app.use; each new writing route is then guarded without being listed.

A path that fails: putting needKey with app.use above everything. Every GET would need the key too, and the list would no longer be open.

When you are stuck: Every request gets 401, or none does

Is the guard on the right path? app.use("/admin", guard) checks only paths below /admin.

Does the header's name match? req.get reads any case, but the spelling must match: x-key is not x-keys.

Is there a return before the 401? Without it, the guard answers and also calls next.

Your turn

Which status should a guard answer when the request has no key, or a wrong one?Tap to reveal
  1. It asks the client to say who it is.

401 Unauthorized.

A middleware sets res.locals.hall = "engine". Where can a route read it, and for how long does it last?Tap to reveal
  1. res.locals belongs to one response.

In res.locals.hall, for that one request only.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.use((req, res, next) => (req.get("x-key") === "brass" ? next() : res.sendStatus(401)));
app.get("/", (req, res) => res.send("in"));
const server = app.listen(3000, async () => {
  const a = await fetch("http://localhost:3000/");
  const b = await fetch("http://localhost:3000/", { headers: { "X-Key": "brass" } });
  console.log(a.status, b.status);
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
401 200
  1. The first request has no key, so the guard answers 401.
  2. The second has the key, so the guard calls next and the route answers 200.

It prints 401 200.

Did you know?

A 401 must say how to log in

A 401 answer has a duty. RFC 9110 says that 401 Unauthorized means the request lacks valid authentication credentials, and that a server sending it must send a WWW-Authenticate header with at least one challenge, which tells the client how to prove who it is. A client whose credentials are known but not enough gets 403 Forbidden instead.

Why it fits here: It answers this topic's question: a 401 must carry WWW-Authenticate, while 403 is for credentials that are not enough.

Source: RFC 9110: HTTP Semantics

Comparing keys in constant time

Comparing a secret key needs care. Node's manual says that crypto.timingSafeEqual compares bytes with a constant-time algorithm, which does not leak timing information that would let an attacker guess one of the values. It suits secrets such as authentication cookies. An error is thrown when the two have different byte lengths, so a guard checks the lengths first.

Why it fits here: It sharpens this topic's key check: crypto.timingSafeEqual compares secrets without leaking clues through timing.

Source: Node.js manual: Crypto (crypto.timingSafeEqual)

In one line

A guard is a middleware that answers early, with return in front, when its check fails, such as 401 for a missing key. Middleware passes what it learns to the route on req or res.locals, which last for one request.

Reading the body

At a glance

A request's body arrives as a stream of bytes. Express has middleware that reads it for you, and turns it into data.

Each body reader handles one Content-Type. The reader express.json() reads JSON, express.urlencoded() reads the body of an HTML form, and express.text() reads plain text, and each puts what it read in req.body. They go above the routes that need them. A body without the right label is not read, so req.body stays undefined, and broken JSON becomes a 400 error.

Take a guess: Is there a body that a route must never parse?

In lesson 02 a server read a body by collecting its chunks with for await, then parsed them. Every route that takes data would need those lines. Express ships middleware that does it once, before the routes: a body parser. It reads the whole body, parses it by its Content-Type, and puts the result in req.body.

express.json() is the one for JSON. It is added once, at the top:

app.js

const express = require("express");
const app = express();
app.use(express.json());
app.post("/readings", (req, res) => res.json({ body: req.body ?? "no body" }));
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ error: err.type ?? "error" }));
const server = app.listen(3000, async () => {
  const sends = [
    ["application/json", '{"value":95}'],
    [null, '{"value":95}'],
    ["application/json", "{value:95}"],
    ["application/json", ""],
    ["application/json", '"just text"'],
  ];
  for (const [type, body] of sends) {
    const r = await fetch("http://localhost:3000/readings", { method: "POST", headers: type ? { "Content-Type": type } : {}, body });
    console.log(type, body || "(empty)", r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

application/json {"value":95} 200 {"body":{"value":95}}
null {"value":95} 200 {"body":"no body"}
application/json {value:95} 400 {"error":"entity.parse.failed"}
application/json (empty) 200 {"body":{}}
application/json "just text" 400 {"error":"entity.parse.failed"}

Go through the five sends. The first had the JSON label and good JSON, and req.body held the object. The second sent the same text without the label; fetch called it plain text, the parser left it alone, and req.body stayed undefined. The parser reads only bodies labelled application/json.

The third had the label but broken JSON. The parser could not read it, so it passed an error to next, with the status 400 and the type entity.parse.failed; the error handler at the end turned that into JSON. The fourth was an empty body with the label, which gives an empty object. The fifth was valid JSON, a lone string, but the parser is strict by default and takes only an object or an array at the top.

The requestreq.bodyWhy
JSON label, good JSONthe object or arrayparsed
no JSON labelundefinedthe parser reads only its own type
JSON label, broken JSONnever reached: a 400 errorentity.parse.failed
JSON label, empty body{}an empty body counts as an empty object
JSON label, a lone string or numbernever reached: a 400 errorstrict mode wants an object or an array

The error handler, the function with four parameters at the end, is the subject of the last section. For now: it is how a parser's error became a JSON answer instead of Express's HTML page.

Forms and plain text

Two more parsers cover the other common bodies. express.urlencoded() reads a form, the name=value pairs that a browser's form or a URLSearchParams sends. express.text() reads plain text and leaves it as a string:

app.js

const express = require("express");
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.text());
app.post("/form", (req, res) => res.json(req.body));
app.post("/note", (req, res) => res.send(`note: ${req.body}`));
const server = app.listen(3000, async () => {
  let r = await fetch("http://localhost:3000/form", { method: "POST", body: new URLSearchParams({ hall: "engine", value: "95" }) });
  console.log(await r.text());
  r = await fetch("http://localhost:3000/note", { method: "POST", body: "three gauges cleaned" });
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

{"hall":"engine","value":"95"}
note: three gauges cleaned

Each parser reads only its own Content-Type, so several can sit together and each body is read by the one that fits. The form's values are strings, as in a query string. The option extended: false keeps the simple reading, without nested objects.

ParserReadsreq.body
express.json()application/jsonthe parsed object or array
express.urlencoded({ extended: false })application/x-www-form-urlencodedan object of strings
express.text()text/plaina string
express.raw()application/octet-streama Buffer of the bytes

Worked example 4

Take new readings as JSON: check that each has a gauge name and a numeric value, keep the good ones, answer 201 with what was saved and 400 otherwise.

What we have: express.json() at the top, an array to keep readings, and a client that sends three bodies, one of them without a value

What we need: 201 for the two good readings, with a running count, and 400 for the one without a value

The plan: read gauge and value from req.body, with a fallback object in case there is no body; check both; push and answer 201, or return a 400

app.js

const express = require("express");
const app = express();
app.use(express.json());
const readings = [];
app.post("/readings", (req, res) => {
  const { gauge, value } = req.body ?? {};
  if (typeof gauge !== "string" || !Number.isFinite(value)) {
    return res.status(400).json({ error: "send a gauge name and a numeric value" });
  }
  readings.push({ gauge, value });
  res.status(201).json({ saved: readings.length, gauge, value });
});
const server = app.listen(3000, async () => {
  const sends = [{ gauge: "boiler", value: 95 }, { gauge: "pump" }, { gauge: "fan", value: 20 }];
  for (const data of sends) {
    const r = await fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) });
    console.log(r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

201 {"saved":1,"gauge":"boiler","value":95}
400 {"error":"send a gauge name and a numeric value"}
201 {"saved":2,"gauge":"fan","value":20}
  1. The destructuring const { gauge, value } = req.body ?? {} pulls the two fields out, and the fallback keeps it working when req.body is undefined.
  2. typeof checks that the name is a string, and Number.isFinite that the value is a real number, not a string or NaN.
  3. The pump's reading had no value, so it got the 400 and was not saved; the count stayed at 1 until the fan's.

The boiler and the fan were saved with 201 (counts 1 and 2), and the pump got 400.

Check: Two saved, one refused, and the count shows that the refused one was never kept.

Another way: answer every problem at once, as lesson 02's checker did: collect a list of problems and return it with the 400.

A path that fails: adding express.json() below the route. The route runs first, while req.body is still undefined, so every reading would fail the check.

When you are stuck: req.body is undefined, or every POST gets 400

Is the parser added above the routes? It must run before the route reads req.body.

Does the client send Content-Type: application/json? Without it, express.json() leaves the body alone.

Is the client's body really JSON? Send JSON.stringify(data), never the object itself, and check that the text parses.

Your turn

A client sends {"value":95} without a Content-Type header to an app with express.json(). What is req.body?Tap to reveal
  1. fetch labels a string body as plain text.

undefined: the JSON parser reads only application/json.

Which parser reads a form sent by a browser, and what kind of values does it give?Tap to reveal
  1. Forms send name=value pairs.

express.urlencoded({ extended: false }), with strings for values.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.use(express.json());
app.post("/", (req, res) => res.send(String(req.body.value * 2)));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/", { method: "POST", headers: { "Content-Type": "application/json" }, body: '{"value":21}' });
  console.log(await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
42
  1. The parser turned the JSON into an object, so req.body.value is the number 21.
  2. 21 times 2 is 42, sent as text.

It prints 42.

Did you know?

Bodies that must stay raw

Some bodies must not be parsed at all. Stripe signs the webhooks it sends to an API, and its documentation says that it needs the raw body of the request to verify the signature. Any change to the raw body makes the check fail, even one made by a framework that parses it. So such a route reads its body with express.raw(), as bytes.

Why it fits here: It answers this topic's question: a signed webhook's body must stay raw, so express.raw() reads it as bytes.

Source: Stripe Docs: Webhooks

Files need multipart

HTML forms have three encodings. The HTML standard lists application/x-www-form-urlencoded, the default, then multipart/form-data and text/plain, and MDN says to use multipart/form-data when a form holds a file input. Express's own readers do not read it. The Express project keeps a separate middleware, multer, which handles multipart/form-data, mainly for uploading files.

Why it fits here: It adds to this topic's readers: a form with files sends multipart/form-data, which multer reads.

Sources: HTML Standard: Form submission attributes; MDN: The form element; multer on GitHub

In one line

express.json(), express.urlencoded() and express.text() read a body of their own Content-Type into req.body. Put them above the routes; without the right label req.body is undefined, and broken JSON becomes a 400 error.

Serving files

At a glance

Not every answer is written by code. Pages, styles and pictures are files that a server only has to send.

The middleware express.static("public") serves the files of the folder public at the top of the address, so public/style.css is at /style.css. Mounted with a path, it serves them under that path. An address that names a folder gets the folder's index.html. Each file's Content-Type comes from its extension. A file that does not exist is not an error: express.static calls next, and the routes below get their turn.

Take a guess: Does express.static serve a file whose name begins with a dot?

Many APIs also serve files: a web page, its stylesheet, its pictures. Files that are sent as they are, the same for everyone, are called static files. express.static("public") is a middleware that serves the files of one folder: a request for /css/site.css gets the file public/css/site.css.

Here are two files in a folder called public, then an app that serves them beside a route. The page shows the files first:

public/index.html

<h1>The yard</h1>

public/css/site.css

body { color: brown; }

app.js

const express = require("express");
const app = express();
app.use(express.static("public"));
app.get("/gauges", (req, res) => res.json({ boiler: 95 }));
const server = app.listen(3000, async () => {
  const asks = [["/", "GET"], ["/index.html", "GET"], ["/css/site.css", "GET"], ["/css/site.css", "HEAD"], ["/gauges", "GET"], ["/missing.png", "GET"], ["/css", "GET"]];
  for (const [p, method] of asks) {
    const r = await fetch("http://localhost:3000" + p, { method, redirect: "manual" });
    const body = (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, "").trim();
    console.log(method, p, r.status, r.headers.get("content-type"), body || "(no body)");
  }
  server.close();
});

Terminal: node app.js

GET / 200 text/html; charset=utf-8 <h1>The yard</h1>
GET /index.html 200 text/html; charset=utf-8 <h1>The yard</h1>
GET /css/site.css 200 text/css; charset=utf-8 body { color: brown; }
HEAD /css/site.css 200 text/css; charset=utf-8 (no body)
GET /gauges 200 application/json; charset=utf-8 {"boiler":95}
GET /missing.png 404 text/html; charset=utf-8 Cannot GET /missing.png
GET /css 301 text/html; charset=UTF-8 Redirecting to /css/

Go down the lines. A request for / got public/index.html: for a folder, express.static sends its index.html. The Content-Type came from each file's extension, .html or .css. A HEAD request got the headers and no body, as for any route.

/gauges had no file, so the middleware called next, and the route answered. /missing.png had neither a file nor a route, so Express's 404 answered. And /css, a folder asked for without its slash, got a 301 to /css/, so that the folder's own links work.

RequestWhat express.static does
a path that names a filesends the file, with the type from its extension
a path that names a folder, with its slashsends the folder's index.html, if it has one
a folder without its slashredirects with 301 to the same path with a slash
a path with no filecalls next, so routes and the 404 come after

The folder's name is not part of the address: the files of public appear at the top, /index.html and not /public/index.html. And the folder is found from where node was started, here the shop's folder, so the app is started from its own folder.

Worked example 5

Serve the site's pages under /site and the API under /api, so that the two never mix.

What we have: the same public folder, and one API route

What we need: the pages at /site/ and below, the API at /api/gauges, and nothing at the top

The plan: mount express.static at /site with app.use, as a router is mounted; keep the API's route on its own path

public/index.html

<h1>The yard</h1>

public/css/site.css

body { color: brown; }

app.js

const express = require("express");
const app = express();
app.use("/site", express.static("public"));
app.get("/api/gauges", (req, res) => res.json({ boiler: 95 }));
const server = app.listen(3000, async () => {
  for (const p of ["/site/", "/site/css/site.css", "/index.html", "/api/gauges"]) {
    const r = await fetch("http://localhost:3000" + p);
    const body = (await r.text()).replace(/[\s\S]*<pre>|<\/pre>[\s\S]*/g, "").trim();
    console.log(p, r.status, body);
  }
  server.close();
});

Terminal: node app.js

/site/ 200 <h1>The yard</h1>
/site/css/site.css 200 body { color: brown; }
/index.html 404 Cannot GET /index.html
/api/gauges 200 {"boiler":95}
  1. Mounted at /site, the middleware sees the rest of the path, so /site/css/site.css reads public/css/site.css.
  2. /site/ is the folder itself, so its index.html answered.
  3. /index.html is outside /site, so the middleware never saw it; with no route either, it got the 404.
  4. The API answered at its own path, untouched by the files.

The pages answer at /site/, the API at /api/gauges, and /index.html at the top is a 404.

Check: Each address went to exactly one place: files under /site, data under /api.

Another way: serve two folders, app.use(express.static("public")) and app.use(express.static("shared")); a file missing from the first is looked for in the second.

A path that fails: writing the address with the folder's name, /site/public/index.html. The folder's name never appears in the address.

When you are stuck: A file answers 404

Is the address written without the folder's name? public/a.css is served at /a.css, or at /site/a.css under a mount.

Was node started from the folder that holds public? The folder is found from there.

Is express.static above a catch-all route? A catch-all above it answers first, and the file is never looked for.

Your turn

With app.use(express.static("public")), at which address is the file public/img/logo.png served?Tap to reveal
  1. The folder's name is not part of the address.

At /img/logo.png.

What does express.static do with a request for a file that is not there?Tap to reveal
  1. It is a middleware.

It calls next(), so the routes, and then the 404, get the request.

mkdir -p public
printf 'hello' > public/a.txt
cat > app.js <<'END'
const express = require("express");
const app = express();
app.use(express.static("public"));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/a.txt");
  console.log(r.headers.get("content-type"), await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
text/plain; charset=utf-8 hello
  1. The file a.txt is in public, so it is served at /a.txt.
  2. Its extension, .txt, gives the type text/plain.

It prints text/plain; charset=utf-8 hello.

Did you know?

Dot files stay hidden

Express 5 hides files whose names begin with a dot. Its migration guide says that express.static's dotfiles option now defaults to ignore, while Express 4 served them. So a folder such as .well-known answers 404, which can break Android App Links and Apple Universal Links. The option dotfiles: "allow" serves such a folder on purpose.

Why it fits here: It answers this topic's question: since Express 5, dot files are ignored unless dotfiles allows them.

Source: Express: Migrating to Express 5

Where the types come from

express.static does not choose types by itself. Express depends on serve-static, which sends files with the package send, which uses mime-types, which reads mime-db. That database calls itself a large database of mime types in a single public JSON file, gathered from IANA, Apache and nginx. A type registered with IANA is pulled in automatically.

Why it fits here: It adds to this topic's types: the extension is looked up in mime-db, a list gathered from IANA, Apache and nginx.

Sources: Express on GitHub: package.json; serve-static on GitHub: package.json; send on GitHub: package.json; mime-types on GitHub: package.json; mime-db on GitHub

In one line

express.static("public") serves a folder's files at the top of the address, or under a mount path; a folder gives its index.html, the type comes from the extension, and a missing file calls next.

The end of the line: a 404 and an error handler

At a glance

Two checkpoints stand at the end of the line, after every route. Every request that gets this far still needs an answer.

The first is an ordinary middleware that answers whatever no route matched, with a 404. The second is an error handler, a middleware with four parameters, (err, req, res, next). It answers every error: a throw, a rejected promise, or a call to next(err). It answers in JSON, and it gives details only for the client's own mistakes, never the server's insides.

Take a guess: How does Express tell an error handler from an ordinary middleware?

Two kinds of request reach the end of the line. Some matched no route at all. Others broke on the way: a route threw an error, or a parser found broken JSON. Express has answers for both, its 404 page and its error page, both in HTML. A JSON API wants its own answers, in JSON, and two middleware at the very end give them:

app.js

const express = require("express");
const app = express();
app.get("/boom", (req, res) => { throw new Error("the boiler burst"); });
app.get("/late", async (req, res) => { throw new Error("a late parcel"); });
app.use((req, res) => res.status(404).json({ error: `no route for ${req.method} ${req.originalUrl}` }));
app.use((err, req, res, next) => {
  console.log("the error handler caught:", err.message);
  res.status(500).json({ error: "something broke on our side" });
});
const server = app.listen(3000, async () => {
  for (const p of ["/boom", "/late", "/nowhere"]) {
    const r = await fetch("http://localhost:3000" + p);
    console.log(p, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

the error handler caught: the boiler burst
/boom 500 {"error":"something broke on our side"}
the error handler caught: a late parcel
/late 500 {"error":"something broke on our side"}
/nowhere 404 {"error":"no route for GET /nowhere"}

The first of the two is an ordinary middleware with no path, written after every route. A request reaches it only if nothing above answered, so it is the API's own 404.

The second has four parameters: (err, req, res, next). That is how Express knows it is an error handler. When a route throws, or calls next(err), Express skips every ordinary middleware and route below and goes straight to the next error handler, passing the error first.

Look at /late. Its handler is async, so its throw became a rejected promise, not a throw. Express 5 catches a rejected promise from a handler and passes it to the error handler too; older Express needed a try and catch, or a package, for that. And the error handler printed the real message on the server, but sent the client only a plain sentence: the inside of a server's failure is for its owner's eyes, not the world's.

FunctionParametersReceives
a route or middleware(req, res, next)requests, while there is no error
an error handler(err, req, res, next)errors only: a throw, a rejected promise, next(err)

Three parameters are not enough

Express counts the parameters of the function. (err, req, res) has three, so Express takes it for an ordinary middleware, and it never receives an error. Keep all four, even when next is not used.

Worked example 6

Let each error carry its own status: a missing gauge answers 404 with its message, a real crash answers 500 with a plain sentence, and an unknown address gets the API's own 404.

What we have: a gauges route that throws an error with a status of 404, a route that crashes, and the two middleware at the end

What we need: 200 for a gauge, 404 with the message for a missing one, 500 without details for the crash, and the JSON 404 for an unknown address

The plan: set err.status before throwing; in the error handler, use err.status or 500; show err.message only when the status is below 500

app.js

const express = require("express");
const app = express();
const gauges = { boiler: 95 };
app.get("/gauges/:name", (req, res) => {
  if (!Object.hasOwn(gauges, req.params.name)) {
    const e = new Error(`no gauge called ${req.params.name}`);
    e.status = 404;
    throw e;
  }
  res.json({ value: gauges[req.params.name] });
});
app.get("/crash", (req, res) => { throw new Error("a broken gear"); });
app.use((req, res) => res.status(404).json({ error: "no such address" }));
app.use((err, req, res, next) => {
  const status = err.status ?? 500;
  res.status(status).json({ error: status < 500 ? err.message : "something broke on our side" });
});
const server = app.listen(3000, async () => {
  for (const path of ["/gauges/boiler", "/gauges/fan", "/crash", "/nowhere"]) {
    const r = await fetch("http://localhost:3000" + path);
    console.log(path, r.status, await r.text());
  }
  server.close();
});

Terminal: node app.js

/gauges/boiler 200 {"value":95}
/gauges/fan 404 {"error":"no gauge called fan"}
/crash 500 {"error":"something broke on our side"}
/nowhere 404 {"error":"no such address"}
  1. The missing fan made the route throw an error with status 404, and the handler sent its message, because a 404 is the client's own mistake.
  2. The crash had no status, so the handler used 500 and hid the message.
  3. /nowhere reached the ordinary middleware before the error handler and got the JSON 404.
  4. Throwing from deep inside a route works the same as calling next(err): both end at the error handler.

The four answers are 200, 404 no gauge called fan, 500 something broke on our side and 404 no such address.

Check: The client's mistakes were explained in words it can act on; the server's own failure was not described.

Another way: add a field for the kind of error, such as code: "GAUGE_NOT_FOUND", so that a client can branch on it without reading the words.

A path that fails: writing the error handler above the routes. An error goes to the next error handler below the place where it happened, so one above the routes is never reached.

When you are stuck: The error handler never runs, or Express's HTML page answers

Does it have four parameters? (err, req, res, next), all four, even if next is not used.

Is it the very last app.use? Errors travel down the line, never up.

Is the 404 middleware above the error handler and below the routes? Each needs its place.

Your turn

How does Express tell an error handler from an ordinary middleware?Tap to reveal
  1. It counts something.

An error handler has four parameters: (err, req, res, next).

A route calls next(new Error("jammed")). Which functions below it run?Tap to reveal
  1. An error skips the ordinary ones.

Only the error handlers below it; ordinary middleware and routes are skipped.

cat > app.js <<'END'
const express = require("express");
const app = express();
app.get("/", (req, res, next) => next(new Error("jammed")));
app.use((req, res) => res.status(404).send("not here"));
app.use((err, req, res, next) => res.status(500).send("caught " + err.message));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/");
  console.log(r.status, await r.text());
  server.close();
});
END
node app.js
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
500 caught jammed
  1. next(err) skips the 404 middleware, which is an ordinary one.
  2. The error handler receives the error and answers 500.

It prints 500 caught jammed.

Did you know?

Express counts the parameters

Express tells an error handler apart by counting its parameters. The router's own code checks fn.length: a function whose length is not 4 is not a standard error handler, and errors pass it by. MDN explains a trap: length counts only the parameters before the first one with a default value, so (err, req, res, next = f) has a length of 3.

Why it fits here: It answers this topic's question: Express reads fn.length, so an error handler needs four plain parameters.

Sources: router on GitHub: lib/layer.js; MDN: Function: length

A 404 is not an error

Express does not treat a missing route as an error. Its FAQ says that 404 responses are not the result of an error, so the error-handling middleware will not capture them. A 404 means only that Express has run every middleware function and route and found that none of them answered. That is why the 404 middleware is an ordinary one.

Why it fits here: It explains this topic's order: a 404 is not an error to Express, so an ordinary middleware after the routes must answer it.

Source: Express FAQ

In one line

After the routes, an ordinary middleware answers what no route matched, and an error handler with four parameters, (err, req, res, next), answers every throw, rejected promise and next(err), in JSON, with details for the client's mistakes only.

Where it is used

Almost everything an API does around its routes is middleware. Here is where each idea of this lesson does its work.

What you learnedWhere it is usedA real example
app.use and nextevery Express appa request id put on every request
a logger on finishevery server in productionmorgan, which writes one line per request
guardsevery API with accountsa token checked before /orders
body parsersevery API that takes dataexpress.json() at the top of a JSON API
express.staticsites and single-page appsan app's built files served beside its API
a 404 and an error handlerevery APIone place that turns every failure into JSON

Much middleware comes from npm and is added with app.use in one line: cors, which lets pages from other sites call the API; helmet, which sets security headers; morgan, the logger. They follow the same rules you learned here: a place in the line, a job, and next.

In the Couriers' Yard, the checkpoints along the belt are middleware, and the clerks at its far end are the 404 and the error handler.

Mistakes and debugging

These are the mistakes that middleware beginners make most, each with the way to see it and the fix.

1. A parser below the routes

A route above the parser runs before the body is read:

app.js

const express = require("express");
const app = express();
app.post("/readings", (req, res) => res.json({ body: req.body ?? "no body" }));
app.use(express.json());
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/readings", { method: "POST", headers: { "Content-Type": "application/json" }, body: '{"value":95}' });
  console.log(await r.text());
  server.close();
});

Terminal: node app.js

{"body":"no body"}

The JSON was sent with its label and still did not arrive. Put express.json() at the top, above every route that reads req.body.

2. An error handler with three parameters

Express counts the parameters. With three, the function is an ordinary middleware, and errors pass it by:

app.js

const express = require("express");
const app = express();
app.get("/crash", (req, res) => { throw new Error("a broken gear"); });
app.use((err, req, res) => res.status(500).json({ error: "caught" }));
const server = app.listen(3000, async () => {
  const r = await fetch("http://localhost:3000/crash");
  console.log(r.status, r.headers.get("content-type"));
  server.close();
});

Terminal: node app.js 2>/dev/null

500 text/html; charset=utf-8

The answer came from Express's own error page, in HTML, not from the handler. Express also wrote the error's stack to the terminal's error stream, which 2>/dev/null hides here. Write all four parameters: (err, req, res, next).

3. A middleware that forgets next

A middleware that neither answers nor calls next leaves the request waiting. The client waits too, until it gives up, and nothing is printed to say why. When a request hangs, look for the middleware on its path that has a way through it without next and without an answer.

4. Answering and then calling next

A guard that answers but has no return in front goes on to next(), and the route then answers a second time, which fails with ERR_HTTP_HEADERS_SENT. Write return in front of every early answer, as in lesson 03.

5. Things in the wrong order

The line is read from the top. A catch-all route above express.static hides every file; a 404 middleware above the routes answers everything with 404; an error handler above the routes never receives an error. Read the app from the top, as a request does.

The debugging corner: follow the request

Add a logger as the first middleware and print req.method and req.originalUrl. Then add a console.log at the top of each middleware and route that the request should pass. The last line printed shows where it stopped.

For a body that does not arrive, print req.get("content-type") and req.body in the route: the label and what the parser made of it.

Quick card

The whole lesson on one card. Come back to it whenever you need a reminder.

app.js

const express = require("express");
const app = express();
app.use((req, res, next) => {
  res.on("finish", () => console.log("log:", req.method, req.originalUrl, res.statusCode));
  next();
});
app.use(express.json());
app.use("/ledger", (req, res, next) => {
  if (req.get("x-key") !== "brass") return res.status(401).json({ error: "a key is needed" });
  next();
});
app.post("/ledger", (req, res) => res.status(201).json({ saved: req.body }));
app.use((req, res) => res.status(404).json({ error: "no such address" }));
app.use((err, req, res, next) => res.status(err.status ?? 500).json({ error: err.status === 400 ? "the body is not valid JSON" : "something broke" }));
const server = app.listen(3000, async () => {
  const send = (headers, body) => fetch("http://localhost:3000/ledger", { method: "POST", headers: { "Content-Type": "application/json", ...headers }, body });
  const answers = [await send({}, '{"value":95}'), await send({ "X-Key": "brass" }, '{"value":95}'), await send({ "X-Key": "brass" }, "{bad"), await fetch("http://localhost:3000/nowhere")];
  for (const r of answers) console.log("client:", r.status, await r.text());
  server.close();
});

Terminal: node app.js

log: POST /ledger 401
log: POST /ledger 201
log: POST /ledger 400
log: GET /nowhere 404
client: 401 {"error":"a key is needed"}
client: 201 {"saved":{"value":95}}
client: 400 {"error":"the body is not valid JSON"}
client: 404 {"error":"no such address"}
When you seeIt meansDo
req.body is undefinedno parser ran, or the label was wrongapp.use(express.json()) at the top; send Content-Type: application/json
a request that never endsa middleware neither answered nor called nextcall next(), or answer, on every path through it
400 with entity.parse.failedthe body is not valid JSONfix the client's JSON; answer it in JSON from the error handler
401 from a guardthe check before the route refused itsend what the guard wants, such as a key
Express's HTML error pageno error handler, or one with three parameters(err, req, res, next), last of all
a file that answers 404a wrong address, or a catch-all above express.staticno folder name in the address; static above the catch-all
ERR_HTTP_HEADERS_SENTa middleware answered, then called nextreturn after every answer

The story: A belt that checks itself

You set the checkpoints in order. First the log, which notes every parcel and, when it leaves, the stamp it got. Then the unwrapper, which opens each parcel and reads what is inside. Then the seal-checker on the ledger lane, which turns back anything unsealed before the ledger bench ever sees it.

At the far end of the belt, one clerk catches any parcel that no bench claimed, and another catches any parcel that broke on the way, and each answers its sender in the yard's own words.

The benches only sort now. "Tomorrow," says the Yardmaster, "we read the parcels themselves more closely: every part of what comes in, and every part of what goes out."

Reagents gathered: middleware, next, app.use, express.json, express.static, error handler.

Sources

  • The Express documentation (CC BY-SA 3.0 US (the site's footer, read 2026-11-15); facts and ideas only)
  • The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
  • MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)