Getting into an airport departure lounge happens in order. The first officer checks your ticket, the second checks your ID, then comes the X-ray. If you pass, you're sent on to the next officer. If you fail, you're sent home right there, and the officers after that never see you.
A request (a message asking a server to do something) can be checked the same way, through middleware. Middleware is a small function standing in a request's path, before the request reaches the handler, the function that does the request's job. Each middleware checks one thing, then chooses: pass the request on to the next middleware by calling next(), or stop it by sending a response (the server's answer) right away. This chain of checkers is the Chain of Responsibility pattern: a request is processed by a chain of functions, one at a time, and each function may add data, reject, or pass it on. In code, each airport officer is one middleware, being sent on to the next officer is next(), being sent home is a response sent early, and the departure lounge is the handler at the end of the chain.
The problem: one handler does everything
In the first version, createShipment checks everything itself. It is the handler for the endpoint (an address on the server for one job) that creates shipments:
function createShipment(req, res) {
const user = TOKENS[req.token]
if (!user) return res.send(401, "Unauthorized")
hits[user] = (hits[user] || 0) + 1
if (hits[user] > 3) return res.send(429, "Too Many Requests")
if (!(req.body.kg > 0)) return res.send(422, "kg must be more than 0")
// ...only here is the shipment created
}
This function checks three things: the token (a code that shows who is sending the request), the request limit (at most 3 per user), and the parcel's weight. Numbers like 401 are HTTP status codes: 401 means the sender isn't known, 429 means too many requests, and 422 means the data isn't valid.
The track, cancel and change-address endpoints need the same token check and request limit. So the checks are written 9 times: 3 in createShipment and 2 in each other endpoint. The moment one endpoint forgets to copy the token check, that endpoint is open to anyone, with no error to tell you.
Middleware: one check, then next()
Split each check into its own function with the same shape, (req, res, next), then line them up as a chain. req is the request object: it holds the token and the request's content. res is the response object, used to send the answer. next is a function that passes on to the next middleware. The handle function at the bottom runs that chain:
const TOKENS = { "tok-sari": "sari", "tok-budi": "budi", "tok-rudi": "rudi", "tok-dewi": "dewi" }
const hits = {} // requests per user
let count = 0
function auth(req, res, next) {
const user = TOKENS[req.token]
if (!user) return res.send(401, "Unauthorized") // stops here
req.user = user // read by the middleware after it
next()
}
function rateLimit(req, res, next) {
hits[req.user] = (hits[req.user] || 0) + 1
if (hits[req.user] > 3) return res.send(429, "Too Many Requests")
next()
}
function validate(req, res, next) {
if (!(req.body.kg > 0)) return res.send(422, "kg must be more than 0")
next()
}
function createShipment(req, res) {
count = count + 1
res.send(201, "KCL-" + String(count).padStart(4, "0") + " for " + req.user)
}
function handle(chain, req) {
const res = { status: null, send(status, body) { this.status = status; this.body = body } }
let i = 0
function next() {
const mw = chain[i] // the next middleware in the chain
i = i + 1
mw(req, res, next)
}
next()
return res.status ? res.status + " " + res.body : "(hanging, no response yet)"
}
const chain = [auth, rateLimit, validate, createShipment]
console.log(handle(chain, { token: "tok-sari", body: { kg: 2 } })) // 201 KCL-0001 for sari
console.log(handle(chain, { token: "", body: { kg: 1 } })) // 401 Unauthorized
console.log(handle(chain, { token: "tok-budi", body: { kg: 0 } })) // 422 kg must be more than 0
handlecalls the first middleware. Eachnext()hands the request to the next one in the array, one at a time, not all at once.- The same
reqtravels the whole chain:authfills inreq.user, andrateLimitreads it. return res.send(...)sends a response and leaves the function.next()isn't called, so the middleware after it never runs.createShipmentat the end of the chain doesn't callnext(). It's the handler doing the actual job.
How the three requests above go through the chain:
| request | auth | rateLimit | validate | createShipment | response |
|---|---|---|---|---|---|
| sari, 2 kg | pass | pass (1) | pass | runs | 201 KCL-0001 for sari |
| no token | reject | not reached | not reached | not reached | 401 Unauthorized |
| budi, 0 kg | pass | pass (1) | reject | not reached | 422 kg must be more than 0 |
Other endpoints use the same chain with their own handler, for example [auth, rateLimit, track]. The token check is written once.
Forgetting next(): the request hangs
Delete next() from rateLimit. Sari's request stops there: rateLimit doesn't reject it, doesn't pass it on, and nobody sends a response. handle returns (hanging, no response yet). Hanging means the request keeps waiting with no answer.
So the app that sent the request gets neither a 500 (the status code for an error on the server) nor an empty response, but no response at all. Express (a framework for building servers with Node.js) has no time limit for this. That app waits until it stops waiting by itself, or until a proxy in front of the server closes the connection. A proxy is a program that passes requests on to the server: nginx, for example, closes it after 60 seconds with status 504. The server log is clean, because nothing in the JavaScript failed.
The opposite is just as dangerous: forgetting return after rejecting, as in if (!user) res.send(401, "Unauthorized"). The 401 goes out, but the function keeps running. next() is still called, the request with no token reaches createShipment, and a shipment is created for undefined. When the handler tries to send a second response, Express throws Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client, after the shipment was saved.
Order decides who gets rejected
rateLimit counts per user, so rateLimit needs the req.user that auth fills in. Send five requests through two chain orders:
| request | [auth, rateLimit, ...] |
[rateLimit, auth, ...] |
|---|---|---|
| #1 sari, 2 kg | 201 KCL-0001 | 201 KCL-0001 |
| #2 no token | 401 | 401 |
| #3 budi, 0 kg | 422 | 422 |
| #4 rudi, 1 kg | 201 KCL-0002 | 429 |
| #5 dewi, 3 kg | 201 KCL-0003 | 429 |
In the second order, rateLimit runs while req.user is still undefined. So all five requests are counted under one shared key, hits["undefined"]. Rudi's request is count number 4, so Rudi is rejected with 429 Too Many Requests on his first request. No error: the code runs, it only rejects the wrong person.
A check that needs data from another check goes after it. A limit per IP (the sender's network address), which doesn't need req.user, usually goes first, so that repeated password guesses are rejected before they reach auth.
Middleware in Express, Koa and the browser
Express uses exactly the same shape, (req, res, next). In Express, an endpoint is called a route. app.use(fn) installs middleware for every route, and app.post("/shipments", auth, rateLimit, validate, createShipment) installs a chain for one route. Rejecting is written return res.status(401).json({ error: "Unauthorized" }). Middleware in Laravel (a PHP framework) is the same: reject, or pass on with return $next($request). Koa (another Node.js framework) uses async (ctx, next) => { ... await next() ... }. In Koa, the code after await next() runs as the chain comes back from the handler. So one middleware can note the time, wait for next(), then calculate how long the request took.
The browser has a similar chain: a click event climbs from the button up through its parent elements, one at a time. Any listener on that path can stop it with event.stopPropagation(). An event climbing like this is called event bubbling.
A chain can also be wired by hand, with a next that takes req:
function m1(req, next) { req.user = "Andi"; next(req) }
function m2(req, next) { req.role = "admin"; next(req) }
function handler(req) { console.log(req.user, req.role) }
m1({}, (r) => m2(r, handler)) // Andi admin
m1 fills in user and passes on to m2. m2 fills in role and calls handler. console.log with two arguments prints them separated by a space: Andi admin.
When you don't need middleware
- The check is for one endpoint only. "This tracking number belongs to the logged-in user" is only used by the cancel endpoint, and that check needs the shipment's data. Write it in the handler.
- Every step must run, whatever happens. Middleware is made to pass on or stop. If no step may stop, just call functions in order.
- The chain is too long. Ten middlewares are ten places to search when a request is rejected for no clear reason.
⚠️ Requests that hang, or get through after a refusal
- Forgetting
next(). The request hangs with no error. Every branch of a middleware's code must end innext()or a response. - Forgetting
returnwhen rejecting. The response has gone out, but the chain keeps running: the handler still does its work, thenERR_HTTP_HEADERS_SENTappears. - The wrong order. A middleware that reads
req.userbeforeauthfills it in rejects the wrong people.
TL;DR: Middleware is a (req, res, next) function in a request's path (a request is a message asking a server to do something). It checks one thing, then passes on to the next middleware with next(), or stops by sending a response (the answer) with return res.send(...). The request is processed by a chain of functions one at a time, with the same req all along: this is the Chain of Responsibility pattern. Forgetting next() leaves the request hanging with no response. Forgetting return lets the chain keep running after a rejection. Order decides who gets rejected: rateLimit, a per-user request limit, must come after auth, which fills in req.user. Otherwise all users are counted together, and a user named Rudi gets a 429 (too many requests) on his first request. Express writes app.post("/shipments", auth, rateLimit, validate, createShipment), Koa uses await next(), and the browser has event bubbling (an event climbing up to the parent elements) with stopPropagation().
⚡ One check, then next()
Write:
function auth(req, res, next) {
const user = TOKENS[req.token]
if (!user) return res.send(401, "Unauthorized") // stops here
req.user = user // read by the middleware after it
next()
}
Meaning: This is a middleware: a small function in a request's path (a request is a message asking a server to do something). req holds the request's data, and res is used to send a response (the answer). A middleware checks one thing, here whether TOKENS[req.token] finds the user who owns the token. Then it chooses: pass on with next(), or stop with return res.send(...). The request is processed by a chain of functions one at a time, with the same req. That's the Chain of Responsibility pattern.
⚡ Forgetting next()
Guess first: the chain is [auth, rateLimit, validate, createShipment], and rateLimit is the middleware that limits the number of requests per user. next() is deleted from rateLimit, and the request from the user Sari passes its check. What does Sari's request get?
No response at all: the request hangs, waiting with no answer. In this lesson, handle (the function that runs the chain) returns (hanging, no response yet), and the server log is clean because nothing failed.
Meaning: Every branch of a middleware's code must end in next() or a response. Forgetting return after rejecting is just as dangerous: the chain keeps running up to createShipment, and a shipment is created for the user undefined.
⚡ Order decides who gets rejected
Write:
const chain = [auth, rateLimit, validate, createShipment]
Meaning: rateLimit counts requests per user from the req.user that auth fills in, so it must come after auth. Swap them, and rateLimit runs while req.user is still undefined, so all requests count as one user. The limit is 3 requests, so the fourth one, Rudi's first request, is rejected with a 429 (too many requests).