Chapter 13 — Express From First Principles: The Middleware Pipeline
Part III · APIs as Contracts | Prerequisites: Ch 10–Ch 12 | Builds: Pulsely reimplemented on Express with explicit cross-cutting middleware
For three chapters now you've designed the contract — the resource model, the status codes, the idempotency keys, the problem documents, the protocols at each boundary. The contract says what a correct response looks like. It says nothing about how the bytes get from the socket to your handler and back, which concerns cross every endpoint at once: authentication, logging, body parsing, validation, turning a thrown SlotConflictError into a 409. Those are the cross-cutting concerns, and in the raw http.createServer world you built earlier they are copy-pasted into every callback. This chapter is about the machine that lets you write each one once, in one place, in a deliberate order — the middleware pipeline.
Here is the promise of the chapter, and it's a small one made precise: Express is not a framework you memorize. It is an ordered array of functions sharing a mutable (req, res) pair, each handed a next callback, iterated by a tiny dispatch loop you could write in an afternoon. Once you see that — really see it, by building the loop yourself — request flow, middleware ordering, and the infamous async-error gotcha all stop being trivia and become consequences you can derive. And by the end you'll feel exactly where Express stops helping, which is the precise pain that justifies Nest in the next chapter. This chapter is code-heavier than the opening ones; the magic only dies when you watch it.
1. The problem: the tangled callback and the request that vanished
Let me start where it actually bites.
Pulsely ships a deploy on a Friday. Among the changes is a route that reads the provider's identity from a JWT before creating a clinical order — say, a lab order dropped mid-visit. The handler is async, because verifying a token and loading the provider both touch the database. Sometime that evening a provider's token expires mid-session, the verify call throws JWTExpired, and then — nothing. No 401 goes back. No error appears in the logs. The clinician's screen sits on a spinner. Sixty seconds later the load balancer's idle timeout fires, the connection is reaped, and the app process is now holding a dangling socket it never finished — reaped here just means the load balancer eventually gave up and killed the idle connection. In plain terms: the server opened a connection for this request and is still waiting to send a reply that never comes. It's a React Query call stuck in loading forever — except this stuck one lives on the server, and each one pins a live TCP connection and a slice of process memory open. Multiply by a few hundred users on expired tokens and you have a slow leak that looks like a memory problem but is really a response that was never sent. Nothing crashed. Nothing 500'd. The request simply evaporated.
We will spend §4 dissecting exactly why that error vanished, because it's the most expensive five minutes of understanding in the whole Express ecosystem. But hold the shape of the failure first: a backend's contract with the client is "exactly one response, always." A request that gets zero responses is worse than one that gets a 500 — a 500 is a ruling; a hang is a held connection, a pinned resource, a clinician staring at nothing, and — as you saw early on — saturation creeping up the chain. The pipeline exists, in large part, to guarantee that promise structurally.
Now rewind to the baseline. Earlier you served HTTP from the raw Node core:
import { createServer } from 'node:http';
const server = createServer((req, res) => {
// ONE callback must do EVERYTHING:
let body = '';
req.on('data', (c) => (body += c)); // parse the body by hand
req.on('end', () => {
if (req.method === 'POST' && req.url === '/encounters') {
const token = req.headers.authorization; // check auth by hand
// ...verify, load provider, validate body, run logic...
res.writeHead(201, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ id: 1 })); // set status + serialize + finish, by hand
} else if (/* twenty more branches */ false) {
// ...
} else {
res.writeHead(404);
res.end();
}
});
});
This works. It also has four diseases that get worse with every endpoint you add:
- Duplication. Auth, JSON parsing, logging, and error handling are identical across all twenty routes, so they get copy-pasted twenty times. Fix a bug in the auth check and you fix it in nineteen other places, or you forget one.
- Tangling. Every concern is braided into every handler. There is no place where "logging" lives; it lives smeared across the whole file.
- The forgotten
res.end(). You've already seen that a response is bytes you must explicitly finish. Miss theres.end()on one branch and that branch hangs forever. The compiler will not save you; there is no "you forgot to respond" error. - Order is invisible and unenforced. Did auth run before you read the body? Before validation? After? In a single nested callback the answer is "wherever you happened to type it," and the cost of getting it wrong is a production incident, not a lint warning.
The naïve fix is helper functions — parseBody(req), requireAuth(req), validate(body). It helps with duplication and not at all with the rest. The reason is subtle and it's the whole motivation for the chapter:
🧭 Mental model. A helper function runs and returns. A middleware gets to decide whether and when the next step runs at all. That extra power — short-circuit (reject early and stop), wrap (start a timer /
try/catcharound everything downstream), and reorder-as-a-unit — is exactly what plain helpers cannot express. Auth must be able to say "stop, 401, do not even reach the handler." A logger must be able to wrap all downstream work to time it. A helper can't do either; it has no handle on the rest of the program. We need composition that controls control flow, not just composition that shares code.
That is the gap Express fills. Not magic — control over whether and when the next thing happens.
2. The mental model: an ordered array, a baton, and two lanes
Hold one picture for the entire chapter, and everything else is a footnote to it.
Express is an ordered array of functions, each sharing one mutable (req, res) pair, each handed a next callback. That is the framework. Not a metaphor for the framework — the framework. Internally it is closer to a list you iterate than to anything you'd call clever.
app.stack = [
requestId, // 0
logger, // 1
express.json(), // 2
authenticate, // 3
getEncounterHandler,// 4 (guarded by method+path)
notFound, // 5
errorMapper, // 6 (4-arg: the error lane)
]
A request enters at index 0 and walks the array. Each function — each link in the chain — does one of exactly three things:
- Handle and end — call
res.json(...)/res.end(). The request is answered; the chain stops here. - Pass through — do its work (attach
req.id, parse the body, start a timer), then callnext()to hand the baton to the next link. - Fail forward — call
next(err)to jump out of the normal flow and onto the error track.
🧭 Mental model — chain of responsibility. Each link is a cooperative participant that decides the fate of the request: handle it, enrich it and yield, or reject it. Control advances only when a link explicitly yields it by calling
next. Express never "moves on for you." If a link neither responds nor callsnext, the request stops dead, mid-pipeline, forever. The whole framework is the discipline of passing the baton exactly once.
That word cooperative is load-bearing. Nothing forces a link to call next. The pipeline runs on trust: each link promises to either finish the request or pass the baton, exactly once. Violate that promise and you get the two canonical bugs — hang (never passed it) and double-send (passed it twice, or responded and also passed it).
Now the second half of the picture. The array isn't one lane; it's two lanes over the same list.
── normal lane ──▶ next() ──▶ next() ──▶ next() ──▶ [respond]
req ─▶ [reqId] ─▶ [log] ─▶ [json] ─▶ [auth] ─▶ [handler] ─▶ [404] ─▶ ╳
│
next(err)
│
└──────── error lane ───────────────▶ [errorMapper(4-arg)]
(skips ALL normal links)
next() walks to the next normal (3-argument) link. next(err) switches lanes: it skips every remaining normal link and runs to the next error-handling link, which Express identifies purely by its arity — a function that takes four arguments, (err, req, res, next). An error hops the request into an express lane that blows past all the normal stops and lands at the one place equipped to turn a thrown thing into an HTTP response. We'll see in §4 that this lane-switch is implemented by literally scanning forward for fn.length === 4. For now: two lanes, one list, and an error is a teleport to the error lane.
A few more reframes that fall straight out of the array model:
- Routing is just conditional middleware.
app.get('/encounters/:id', handler)is not a special construct. It is a middleware that says "runhandleronly ifmethod === 'GET'and the path matches/encounters/:id; otherwise callnext()and let the request continue down the array." A route is middleware with a method+path guard. Nothing more. - A router is a sub-array.
app.use('/api', apiRouter)mounts a router that contains its own ordered list. Composition is recursive: the pipeline is an array that can contain arrays. The prefix/apiis stripped before the sub-array sees the path. - The request's life is a single pass down a funnel. It enters once, flows through the stops in declared order, and must exit exactly once with one response. Two
res.send()calls and a forgottennext()are the same category of bug: a violation of "exactly one pass, exactly one exit."
📎 Borrowed on credit: the request-scoped context. Notice that every link reads and writes the same
reqobject — auth attachesreq.user, validation attachesreq.validated, the handler reads both. That shared mutable bag is how middleware communicate. It works, and it's also the seam where Express's typing gets weak and "where didreq.usercome from?" becomes a real question. Nest replaces this ad-hoc bag with a typed, container-managed request context. We name the tension here and resolve it in Chapter 14; for now, just see that thereqobject is the pipeline's shared memory.
🧭 The shape is older and wider than Express. It's the Servlet
Filterchain in Java (chain.doFilter(req, res)is the same baton), Rack middleware in Ruby, ASP.NET Core's middleware, and Go'shttp.Handlerdecorators. Learn the ordered-list-with-a-baton once and you've learned the request pipeline of every mainstream backend. Express is just the most naked version of it.
3. Theory & invariants
A mental model tells you how to picture the pipeline. Invariants tell you what must stay true or the pipeline misbehaves. These four are the load-bearing rules; almost every Express bug is a violation of one of them.
🔑 The exactly-once-response invariant. For each request, exactly one terminal action (
res.end,res.send,res.json, ...) must occur. Zero terminal actions = the request hangs (the Friday-night incident). Two =ERR_HTTP_HEADERS_SENT, because once you've written the status line and headers you cannot write them again. Every other invariant in this section exists in service of this one. When you debug Express, your first two questions are always: did something respond, and did only one something respond?
🔑 The
next-at-most-once invariant. Within a single middleware,nextmust be called at most once. Call it twice and you run the rest of the chain twice — the handler executes twice, the response is sent twice, you tripERR_HTTP_HEADERS_SENT. The classic trigger: a function that callsnext()on the happy path and alsonext(err)in a callback, withoutreturn-ing after the first. The fix is a reflex:return next(...), always, so the function cannot continue past its hand-off.
🔑 The order-is-semantics invariant. The array order is the program. This is not a style preference like brace placement; reordering the array changes behavior. The body parser must precede any handler that reads
req.body, or the handler seesundefined. The logger must come first if it is to time everything. Authentication must precede authorization. The error handler must come last, after every route, or it can't catch their errors. When someone says "middleware ordering is just convention," they are wrong in a way that ships bugs: the order is executable.
🔑 The arity-is-the-type invariant. Express distinguishes a normal middleware from an error-handling middleware by function arity — how many parameters it declares.
(req, res, next)(three) is normal;(err, req, res, next)(four) is an error handler. This is a genuinely leaky abstraction, and it leaks in a way that bites: if you write your error handler as(err, req, res)— dropping the unusednextto satisfy a linter — Express counts three parameters, classifies it as normal middleware, and it never runs on the error lane. The arity is the type tag. You must declare all four even if you ignore one.
With the invariants pinned, a few definitions and rules that the rest of the chapter leans on:
Vocabulary, nailed down. A middleware is any function in the stack. A handler is a terminal middleware mounted on a route (it usually responds rather than calling next). A router is a middleware that contains its own ordered sub-stack. Terminal means "responds and stops"; pass-through means "calls next." Short-circuit is a middleware ending the request early (auth returning 401 before the handler runs). Fallthrough is what happens when no route matches — the request reaches the end of the stack having not been answered, which is your cue to send a 404. Error-handling middleware is the 4-arg link on the error lane.
Routing & matching semantics. For route handlers, first match wins — the first app.get('/encounters/:id', ...) whose method and path match handles the request, and routes declared later don't get a look. But app.use(...) middleware is prefix-matched and cumulative — every app.use('/api', ...) whose prefix matches runs, in order, because middleware is meant to stack. Specific routes should be declared before generic ones (/encounters/recent before /encounters/:id, or :id will swallow recent).
Mounting & prefix stripping. app.use('/api', router) runs router for any path under /api, and strips the /api prefix so the router's internal routes are written relative (router.get('/encounters') answers GET /api/encounters). Composition is recursive: a router is just a stack-in-a-stack, and the prefix is bookkeeping at the mount point.
Throwing vs next(err). These are not the same, and the difference is the entire async gotcha (§4). In synchronous code, throw inside a middleware is caught by Express and converted to next(err) for you. In asynchronous code (a rejected Promise in an async function), throw is not caught by Express 4 — the rejection escapes into the void. next(err) always works, sync or async, because it's an explicit call. Hold that distinction; §4 makes it mechanical.
📎 Borrowed on credit: streams are one-shot. The body parser (§4) consumes
reqas a readable stream — and a stream can be read exactly once (the bytes flow past and are gone). That's why a second body parser, or a handler trying to re-readreq, gets nothing. The full treatment of streams and backpressure is Chapter 8; here we only need the consequence: parse the body once, early, and stash the result onreq.body.
4. Under the hood: building tinyexpress, and why your error vanished
Nothing kills the magic like rebuilding the engine. So let's build Express's core — enough to run real routes — in about sixty lines, then use it to explain the async-error gotcha mechanically rather than mystically.
tinyexpress: the whole framework, de-magicked
Express's real router is a few hundred lines of edge cases, but its heart is an index-driven loop over an array. Here it is.
import { createServer, IncomingMessage, ServerResponse } from 'node:http';
type Req = IncomingMessage & { params?: Record<string, string> };
type Res = ServerResponse;
type Next = (err?: unknown) => void;
type Middleware = (req: Req, res: Res, next: Next) => void;
type ErrorMiddleware = (err: unknown, req: Req, res: Res, next: Next) => void;
interface Layer {
method?: string; // undefined => matches any method (a "use")
match: (path: string) => Record<string, string> | null;
handle: Middleware | ErrorMiddleware;
}
function compilePath(path: string) {
// '/encounters/:id' -> /^\/encounters\/([^/]+)\/?$/ with param names captured.
const names: string[] = [];
const re = new RegExp(
'^' + path.replace(/:[^/]+/g, (m) => { names.push(m.slice(1)); return '([^/]+)'; }) + '/?$'
);
return (p: string) => {
const m = re.exec(p);
if (!m) return null;
const params: Record<string, string> = {};
names.forEach((n, i) => (params[n] = m[i + 1]));
return params;
};
}
function createApp() {
const stack: Layer[] = [];
const add = (method: string | undefined, path: string, fn: Middleware | ErrorMiddleware) =>
stack.push({ method, match: compilePath(path), handle: fn });
const dispatch = (req: Req, res: Res) => {
let i = 0;
const next: Next = (err?: unknown) => {
const layer = stack[i++]; // grab current, advance pointer
if (!layer) { // walked off the end of the array
if (err) { res.statusCode = 500; res.end('Internal Server Error'); }
else { res.statusCode = 404; res.end('Not Found'); }
return;
}
const isErrorLayer = layer.handle.length === 4; // ARITY is the type tag
const methodOk = !layer.method || layer.method === req.method;
const params = methodOk ? layer.match(req.url!.split('?')[0]) : null;
if (err) {
// ERROR LANE: skip everything that isn't a 4-arg handler.
if (isErrorLayer && methodOk && params !== null) {
req.params = params;
return (layer.handle as ErrorMiddleware)(err, req, res, next);
}
return next(err); // keep scanning forward for a 4-arg layer
}
// NORMAL LANE: skip 4-arg error handlers; run matching 3-arg layers.
if (!isErrorLayer && methodOk && params !== null) {
req.params = params;
try {
return (layer.handle as Middleware)(req, res, next);
} catch (e) {
return next(e); // SYNC throw -> error lane. (Note: sync only!)
}
}
return next(err); // didn't match -> advance
};
next(); // kick off the walk
};
return {
use: (fn: Middleware | ErrorMiddleware) => add(undefined, '.*', fn),
get: (p: string, fn: Middleware) => add('GET', p, fn),
post: (p: string, fn: Middleware) => add('POST', p, fn),
listen: (port: number, cb?: () => void) =>
createServer((req, res) => dispatch(req, res)).listen(port, cb),
};
}
Read dispatch slowly, because three myths die in it:
🧭
nextis a closure, not a keyword.nextis just a function that closes over the indexi. Calling it runsstack[i]and bumpsi. There is no language magic — "calling next" is "increment a pointer and invoke the next array element." That's why callingnext()twice runs the rest twice (you advanced and invoked twice), and why not calling it stops the walk dead (the pointer never advances, nothing else ever runs). The exactly-once-response and at-most-once-nextinvariants from §3 are now obvious mechanics, not rules to memorize.
🧭 The error lane is a forward scan for arity 4. When
next(err)is called, every iteration checkslayer.handle.length === 4and skips anything that isn't an error handler, callingnext(err)again to keep scanning. This is — almost literally — how Express's realrouter/index.jsworks. The 4-arg rule isn't a convention bolted on top; it's the only way the dispatcher can tell which lane a layer belongs to. The leaky abstraction from §3 is now a one-lineif.
🧭 Routing is conditional middleware, proven. A
get/postlayer carries amethodand a compiledmatch. If either fails, the layer falls through tonextand the request keeps walking. There is no separate "router" — routes are layers with predicates, exactly as claimed in §2.
Port one Pulsely route onto it to prove it runs:
const app = createApp();
app.use((req, res, next) => { console.log(req.method, req.url); next(); }); // logger
app.get('/encounters/:id', (req, res) => {
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ id: req.params!.id, type: 'progress-note' }));
});
app.listen(3000);
// GET /encounters/42 -> {"id":"42","type":"progress-note"} (params populated by compilePath)
Real Express adds path-to-regexp (a far more capable compilePath), prototype-patched req/res (more on that below), sub-routers, and a thousand conveniences. But the skeleton is this. When you're lost in Express later, come back to dispatch: which index am I at, which lane am I on, did someone respond.
The async-error gotcha, mechanically
Now we can explain the Friday-night vanishing act with zero hand-waving. Look again at the try/catch inside dispatch's normal lane:
try {
return (layer.handle as Middleware)(req, res, next);
} catch (e) {
return next(e);
}
That try/catch catches a synchronous throw. Now consider an async handler:
app.post('/orders', async (req, res, next) => {
const provider = await verifyToken(req.headers.authorization); // throws JWTExpired
const order = await orders.create(provider.id, req.body); // e.g. a lab order
res.status(201).json(order);
});
Here is the mechanism, and the fastest way to accept it is an analogy you already own. Think of it exactly like calling something that hands you a React Query promise: the call returns to you right away with a pending promise in hand — the fetch hasn't failed yet. In your components React Query holds onto that promise and shows the error when it later rejects. Express 4 does not hold onto it. Now the same thing spelled out mechanically: when the dispatcher calls this handler, the handler runs up to the first await and immediately returns a Promise — synchronously, before verifyToken ever rejects. The try/catch sees a clean synchronous return (a Promise object) and is satisfied. Control goes back to dispatch. Express does not await your handler — it has no reference to the Promise, no .catch attached. Later, verifyToken rejects. The rejection has nowhere to go: the try/catch already exited, next was never called, the response is never sent. Node surfaces it as an unhandledRejection (a process-level event, not an HTTP response), and the request hangs until the load balancer reaps it. That is the entire incident, and it is structural, not a bug in your code: Express 4's next is a plain callback contract that predates Promises, and the dispatcher cannot await something it was never handed.
This is not a corner case in Pulsely. Half your handlers await an external partner — an eligibility 271 coming back, a lab result posted to a callback, an e-Rx acknowledgment, a claim handed to the clearinghouse — so half your handlers are exactly the async handlers this bug targets. A dropped rejection here isn't a cosmetic hang; it's a lost claim or a critical result that never surfaced.
🛑 What we deliberately did not explain here. Why an
asyncfunction returns synchronously at the firstawaitis the microtask/event-loop machinery of Chapter 7. We're using the consequence — "the handler returns a Promise before it rejects, and Express never sees the rejection" — without re-deriving the event loop. If "returns synchronously then rejects later" feels slippery, that's the chapter to revisit; here it's a tool.
There are exactly three fixes, and a senior engineer knows all three and why each works.
Fix 1 — manual try/catch + next(e). Make the rejection explicit:
app.post('/orders', async (req, res, next) => {
try {
const provider = await verifyToken(req.headers.authorization);
const order = await orders.create(provider.id, req.body);
res.status(201).json(order);
} catch (e) {
next(e); // hand the rejection to the error lane, by hand
}
});
Correct, and unbearable — twenty handlers, twenty identical try/catch blocks, one of which you'll forget, reintroducing the exact bug.
Fix 2 — an asyncHandler wrapper. Lift the try/catch into a higher-order function, written once:
const asyncHandler =
(fn: (req: Req, res: Res, next: Next) => Promise<unknown>) =>
(req: Req, res: Res, next: Next) =>
Promise.resolve(fn(req, res, next)).catch(next); // attach the .catch Express forgot
app.post('/orders', asyncHandler(async (req, res) => {
const provider = await verifyToken(req.headers.authorization);
const order = await orders.create(provider.id, req.body);
res.status(201).json(order);
}));
The wrapper takes the Promise the dispatcher ignored and attaches .catch(next) to it. A rejection now becomes next(err) — back onto the error lane, exactly as if it had thrown synchronously. This is what express-async-handler and friends do in five lines. Until you're on Express 5, wrap every async handler; the discipline is "no naked async middleware."
Fix 3 — Express 5's native forwarding. Express 5 finally awaits your handler internally — if a middleware returns a Promise that rejects, the framework routes it to the error lane automatically. The reason this took a major version is the at-most-once-next invariant: Express 4 promised that returning a value from a middleware did nothing (only next/res advanced the request). Awaiting return values and auto-forwarding rejections changes that contract, so it couldn't be done without risking double-next in code that already called next and returned a Promise. Express 5 redefines the contract carefully; on Express 5 you can drop the wrapper for the common case.
🏭 In production, treat the wrapper as load-bearing on Express 4 and verify the Express-5 behavior with a test rather than trusting the blog post. The failure mode — a hung request, no log — is invisible until a user complains, which means it must be caught by a test (a
supertestrequest asserting the handler's thrown error produces a status, not a timeout), not by code review. Bugs whose signature is "silence" need automated tripwires.
Where req and res come from, and body parsing
Two more pieces of "magic" worth dissolving.
req and res are not Express types. They are Node's IncomingMessage and ServerResponse — the raw stream objects you met earlier — that Express augments by patching their prototypes. res.json(...), res.status(...), req.params are methods Express monkey-patches onto Node's prototypes at startup. That's why res.json exists in Express and not in raw http: same underlying object, extra methods bolted on. Convenient, and weakly typed — req.user is any until you declare it, because it's a property nobody's prototype actually owns.
Body parsing is itself just middleware, and seeing that closes the loop on streams:
function jsonParser(limit = 100_000): Middleware {
return (req, res, next) => {
let body = '';
let size = 0;
req.on('data', (chunk) => {
size += chunk.length;
if (size > limit) { res.statusCode = 413; return res.end('Payload Too Large'); } // DoS guard
body += chunk;
});
req.on('end', () => {
try { (req as any).body = body ? JSON.parse(body) : {}; next(); }
catch { next(new Error('Invalid JSON')); }
});
req.on('error', next);
};
}
express.json() is essentially this: a stream consumer that buffers req, JSON.parses it, assigns req.body, and calls next. Two consequences fall straight out of the streams invariant from §3. It must run before any handler that reads req.body, or the handler sees undefined (the order invariant, with teeth). And you cannot parse the body twice, because req is a one-shot stream — once jsonParser drains it, the bytes are gone, so a second parser or a handler re-reading req gets nothing. The limit is not optional decoration: without it, an attacker streams a multi-gigabyte body and you buffer all of it into memory (more in §8).
🧭 JVM contrast that teaches. In plain terms first: Java gives each incoming request its own worker — a thread — that just sits and waits (blocks) on each step until it finishes. So when something throws, it throws on that same waiting worker and gets caught right there, normally. Node instead has one worker shared by everyone, so it can't sit and wait — it returns a promise and moves on, which is exactly the hole the async error falls through. Now the Java names for that mechanism: the Servlet
FilterChainis the same baton —chain.doFilter(req, res)isnext()— but synchronous and thread-per-request. Each filter blocks its thread until the chain returns; concurrency comes from running many threads, not from yielding an event loop. Express'snextyields to the single event loop; the Servlet chain pins a thread. That difference is why the async-error gotcha is a Node-specific affliction: a synchronous chain has no "returns a Promise now, rejects later" hole — the throw happens on the same stack the filter is blocking on. (Skippable Spring aside: Spring layers onHandlerInterceptorwith separatepreHandle/postHandle/afterCompletionhooks — explicit "before" and "after" slots around the handler — which Express's single-passnextmodel cannot directly express; to do "after" work in Express you register before and listen onres.on('finish').) Park that limitation; it's a thread we pull in §7 and pay off in Chapter 14.
5. In production: the canonical Pulsely stack, ordered on purpose
Here is the Pulsely increment: the full HTTP surface — patients, encounters, appointment slots, orders, worklist — reimplemented on Express with a deliberate, ordered middleware stack. The order is the whole lesson, so we'll justify it link by link. This is the diagram to internalize:
REQUEST
│
▼
┌──────────────────────┐ why it's HERE
│ 1 requestId │ first, so every later log line and downstream call shares an id
│ 2 helmet (sec headers)│ cheap, unconditional; set safe headers before any work
│ 3 cors │ decide cross-origin before spending effort on the request
│ 4 rateLimit │ shed abusive load BEFORE expensive auth/db work (see §8)
│ 5 pino-http (logger) │ wraps everything downstream so it can TIME the full request
│ 6 express.json{limit}│ parse body once, with a size cap, before any consumer reads it
│ ── /api router ── │
│ 7 authenticate │ establish identity before any handler or authorization
│ 8 validate(schema) │ per-route: reject malformed input before the handler (after auth)
│ 9 handler │ the actual ruling: touch state, return a representation
│ 10 notFound (404) │ fallthrough: nothing matched -> one response, not a hang
│ 11 errorMapper (4-arg)│ LAST: the only place a thrown error becomes an HTTP status
└──────────────────────┘
│
▼
RESPONSE (exactly once)
Wired up, abbreviated but faithful:
import express from 'express';
import helmet from 'helmet';
import cors from 'cors';
import rateLimit from 'express-rate-limit';
import pinoHttp from 'pino-http';
import { randomUUID } from 'node:crypto';
const app = express();
app.use((req, res, next) => { (req as any).id = randomUUID(); next(); }); // 1 request id
app.use(helmet()); // 2 security headers
app.use(cors({ origin: ['https://app.pulsely.health'] })); // 3 origin policy
app.use(rateLimit({ windowMs: 60_000, max: 300 })); // 4 shed load early
app.use(pinoHttp({ genReqId: (req) => (req as any).id })); // 5 log + time all
app.use(express.json({ limit: '100kb' })); // 6 parse body, capped
const api = express.Router();
api.use(authenticate); // 7 identity for /api/*
api.post('/orders', validate(createOrderSchema), asyncHandler(ordersController.create)); // 8,9
api.get('/encounters/:id', asyncHandler(encountersController.get)); // 9
// ...patients, appointment slots, worklist...
app.use('/api', api);
app.use((req, res) => res.status(404).json(problem('not-found', 404))); // 10 fallthrough
app.use(errorMapper); // 11 terminal, 4-arg
The ordering decisions, each with a reason you could defend in a review:
- Request-id first so every log line and every downstream call — a gRPC call, the database query, the claim posted to the clearinghouse — can carry the same correlation id. If it ran later, the earliest logs would lack the id.
- Logger before everything substantive because a logger that wraps downstream work can time it. Mount it after the router and some requests go unlogged; mount it before, and
res.on('finish')fires for every request with full latency and final status. - Rate limit before auth and the database — this is a security decision, covered in §8. Shedding load before you spend a database round trip verifying a token is the difference between throttling an attacker cheaply and letting them exhaust your connection pool.
- Body parse before any handler, with a
limit. Order invariant + DoS guard in one link. - Authenticate before authorize before the handler. Identity is established once, on the
/apirouter, so every protected route inherits it; per-routevalidateruns after auth, so an unauthenticated attacker can't make you spend validation CPU on a hostile body (and can't probe which fields exist via validation error messages). In a PHI system this ordering is doubly load-bearing: an unauthenticated caller must never reach code that touches a chart or leaks whether a patient exists. - 404 fallthrough as a normal middleware at the end: if the request walked the whole stack unanswered, something must respond, or it hangs. The fallthrough guarantees a ruling.
- Error mapper last, and 4-arg. It must come after all routes (so it can catch their errors) and must declare four parameters (so the dispatcher puts it on the error lane).
The single error-mapping middleware
This is where the error taxonomy you designed earlier lands in HTTP. Domain code throws domain errors and knows nothing about status codes; one place — and only one — translates them:
function errorMapper(err: any, req: any, res: any, next: any) { // 4 args: ON the error lane
const known: Record<string, number> = {
NotFoundError: 404, ValidationError: 422, AuthError: 401, ForbiddenError: 403,
SlotConflictError: 409, // e.g. two front-desk staff grabbing the same 9:00 slot
};
const status = known[err?.name] ?? 500;
if (status >= 500) {
req.log.error({ err, reqId: req.id }, 'unhandled'); // full stack -> logs, keyed by req id
}
res.status(status).json({ // problem+json, generic on 500
type: `https://errors.pulsely.health/${status === 500 ? 'internal' : err.name}`,
title: status === 500 ? 'Internal Server Error' : err.message,
status,
instance: req.id, // correlation id back to the client
});
}
🏭 The rule is "one chokepoint, no exceptions." Forbid ad-hoc
res.json({ error })in handlers; every error exits through this one filter. That gives you a single place to ensure stack traces never reach the client (a500leaks'Internal Server Error'and a correlation id, the stack goes to logs), a single place where the problem+json shape is enforced so it can't drift across twenty handlers, and a single place to get the 4xx-vs-5xx split right so clients retry correctly. Centralized error shaping is the same principle as Spring's@ControllerAdvice— and it's the principle Nest will nameExceptionFilter.
Graceful shutdown — closing the hang for good
The pipeline guarantees exactly-once-response per request; graceful shutdown guarantees the process doesn't strand in-flight requests when it's told to die:
const server = app.listen(3000);
process.on('SIGTERM', () => {
server.close(() => process.exit(0)); // stop accepting new conns; let in-flight finish
setTimeout(() => process.exit(1), 10_000).unref(); // hard cap so a stuck request can't block forever
});
On deploy, the orchestrator sends SIGTERM; server.close stops accepting new connections and drains the ones in flight; the timeout is a backstop so a wedged request can't hold the shutdown hostage. Without this, a deploy mid-request is its own version of the Friday-night hang — a connection severed with no ruling, a half-submitted claim. This belongs in Chapter 33's reliability toolkit; we wire the minimum here so the failure can't recur.
Wiring dependencies by hand — and feeling the seam
Middleware and handlers need a logger, a database handle, a config object. With no container, you inject them by closure:
function makeAuthenticate(deps: { verify: (t: string) => Promise<User> }) {
return async (req: any, res: any, next: any) => {
try { req.user = await deps.verify(req.headers.authorization ?? ''); next(); }
catch (e) { next(e); }
};
}
const authenticate = makeAuthenticate({ verify: jwtVerify }); // composition root, by hand
This works, and it works for a while. But watch what happens as Pulsely grows: ordersController needs the db, the clearinghouse/lab-order gateway, the alerting service, and the logger; each of those needs its own dependencies; and the place where you new everything up and thread it through — the composition root — becomes a sprawling, fragile function nobody wants to touch. Every new dependency means editing the constructor call, the wiring, and the test setup, and keeping three mocks in sync.
📎 Borrowed on credit: the container. That growing composition-root tax is not a flaw in your discipline — it's the absence of a container: something that knows how to build the dependency graph, owns object lifetimes, and hands finished objects to whoever declares they need them. Hand-wiring is honest and visible at small scale and unbearable at large scale. We name the seam here, on purpose, with the manual wiring in front of you so the pain is concrete. Chapter 14 is the resolution: dependency injection and the Nest module system.
Finally, you test the pipeline — including its ordering — with supertest, asserting not just status bodies but ordering effects:
import request from 'supertest';
it('rejects with 401 before validation runs', async () => {
const res = await request(app).post('/api/orders').send({ garbage: true });
expect(res.status).toBe(401); // auth short-circuited; validation never ran
});
it('async handler error reaches the error mapper (no hang)', async () => {
const res = await request(app).get('/api/encounters/explodes');
expect(res.status).toBe(500); // a STATUS, not a timeout -> the wrapper works
});
That second test is the tripwire for the Friday-night bug. If the async wrapper is missing, this test times out instead of returning 500 — turning an invisible production hang into a visible red build.
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
Async error swallowed → request hangs.
Signature: a client times out (often at the LB's 60s), there is no log and no 500, and you may see an unhandledRejection warning unconnected to any request.
Fix: never write naked async middleware on Express 4. Wrap with asyncHandler (attaches the .catch(next) Express forgot) or upgrade to Express 5's native forwarding. The diagnostic tell: silence. A hang with no error is almost always an unawaited rejection.
Error handler registered too early. Signature: errors aren't mapped; you get Express's default HTML error page or a hang, even though your error middleware "exists." Fix: register the 4-arg error middleware after every route. It can only catch errors from layers that come before it in the array (the error lane scans forward).
Error handler with the wrong arity.
Signature: same as above — your error handler never runs — but the cause is sneakier: a linter told you to drop the unused next, so you wrote (err, req, res).
Fix: declare all four parameters, (err, req, res, next), even if you ignore next. Arity is the type tag; three params makes Express treat it as normal middleware.
Forgot next() / forgot to respond.
Signature: the request hangs; eventually the socket 502s. Works in tests that happen to hit a different branch.
Fix: every non-terminal middleware must call next() or send a response, on every path through it (including early-return branches). The 404 fallthrough is your net for "no route matched"; it is not a net for "a middleware silently dropped the baton."
Called next() and res.send().
Signature: ERR_HTTP_HEADERS_SENT crash, or the chain runs twice and double-responds.
Fix: treat sending as terminal — return res.json(...), and return next(...). The return makes it impossible to fall through and do both.
Body parser after the handler.
Signature: req.body is undefined in the handler; works once you move a line.
Fix: parsing precedes every consumer. Check stack order — the order invariant has teeth here.
Auth and validation in the wrong order. Signature: unauthenticated requests trigger expensive validation or DB work; validation error messages leak which fields/records exist to anonymous callers. Fix: authenticate → authorize → validate → handle. Ordering is a security control (§8), not a style choice.
Cross-cutting middleware mounted too late. Signature: some requests are un-logged or un-rate-limited; the gap correlates with specific routes mounted before the logger. Fix: observability and protection (request-id, logger, rate-limit) go first, before any router, so coverage is total.
Caching request-scoped data on module globals.
Signature: a value set for one request bleeds into another (a clinician intermittently sees another patient's chart under load — a reportable HIPAA breach, not a cosmetic glitch).
Fix: per-request state lives on req, never in module scope. The req object is the request's memory; module scope is shared across all concurrent requests on the single event loop.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand.
Explicit pipeline (Express) ↔ declarative framework (Nest).
Express gives you total visibility and zero magic: the stack is an array you can read top to bottom, and every behavior is a function you can step into. The cost is that you hand-wire ordering, dependency injection, and async-error safety on every project, and the discipline doesn't scale — a 40-line composition root, an asyncHandler someone forgot, an ordering bug nobody caught. You lean Express when the app is small, the team values legibility over structure, or you're teaching/debugging the pipeline itself. You reverse toward Nest when the app outgrows hand-rolled structure: many modules, shared providers, lifecycle needs, a team large enough that "remember to wrap async handlers" stops being reliable. The honest framing: Express's magiclessness is a feature until the wiring you do by hand becomes the bug surface.
Global ↔ per-route middleware.
Global middleware (app.use) is DRY but runs for everything — a perf cost on every request and, worse, accidental coverage (a global auth might silently protect a route you meant to be public, or a public route slips out from under it). Per-route middleware is explicit and verbose. The rule: per-route for security-sensitive ordering (auth/validation co-located with the route you're protecting, so the protection is visible at the route), global only for genuinely universal cross-cutting concerns (request-id, logging).
Throw ↔ next(err).
Throwing reads beautifully and is safe in synchronous code (Express converts it) or on Express 5. next(err) is universal — sync or async, any version — but noisy. Pick by version and convention: on Express 4, next(err) (or a wrapper that turns throws into it) is the only safe universal choice; on Express 5 you can throw freely and let native forwarding catch it.
Monkey-patched req/res ↔ a typed context object.
Express augments Node's stream objects with extra methods and lets you stash anything on req. Convenient, weakly typed, globally mutable — "where did req.user come from and what's its type?" is a real question with no compiler answer. The rejected alternative is a passed context object (Koa's ctx, Nest's request scope): better typing, explicit shape, more ceremony. Express picks convenience; Nest picks the typed context. Neither is free.
Middleware functions ↔ AOP / decorators.
Express does everything as ordered functions — debuggable, obvious, greppable, with ordering visible in the array. Spring and Nest use decorators and interceptors — terse, declarative, and order-hiding (a @UseGuards doesn't show you where in the pipeline it runs). Name the cost honestly: decorators trade visibility for brevity. When ordering is a security control, visible-but-verbose beats terse-but-hidden.
Single-pass next ↔ around-advice / lifecycle hooks.
This is the thread from §4's JVM contrast, and it's the direct Nest motivation. Express's next is single-pass: a middleware runs before downstream work, and the only way to do after work (response-time logging, cleanup) is to register before and hook res.on('finish'). Spring's HandlerInterceptor has explicit preHandle/postHandle/afterCompletion slots; Nest has interceptors that genuinely wrap the handler (transform the return value, observe completion) and guards that read route metadata. Express cannot directly express "around" logic — it fakes it with event listeners.
🚫 A framing this book rejects. "Express is just an old, primitive Nest — once you know Nest you can forget Express." Backwards. Nest's middleware is Express middleware, its guards are your
requireAuth, its pipes are yourvalidate, its exception filters are your error mapper, and under the hood it runs on Express (or Fastify) by default. Nest doesn't replace the pipeline; it names the slots in the pipeline you just hand-built and hands you a container to wire them. If you can't reason about the Express array and its two lanes, Nest's lifecycle is a sequence of decorators you cargo-cult. Learn the engine first; the framework is ergonomics layered over it. That's the entire pedagogical bet of this chapter — and the reason it comes before Chapter 14, not after.
8. Security & scale notes
Security and scale aren't a separate section of the codebase; in the pipeline they're properties of the order and content of the array. In a HIPAA system that's not an abstraction: a mis-ordered link is how a chart reaches the wrong clinician.
Ordering bugs are vulnerabilities. This is the chapter's sharpest security claim. Auth-after-handler exposes business logic and PHI to anyone. Validation-before-auth lets an anonymous attacker spend your CPU and leak field/record existence through error messages. Rate-limit-after-auth means an attacker exhausts your connection pool verifying tokens before you ever throttle them. The correct order is itself a control: rate-limit → authenticate → authorize → validate → handle. Every link doing cheap, untrusted-input-safe work sits before every link doing expensive or trusted work. Misorder the array and you've shipped a vuln that no amount of correct handler code can fix — and in healthcare, "a broken access check reached a chart" is a reportable breach, not a bug ticket.
The body parser is an attack surface. express.json parses attacker-controlled input, so:
- Set
limit. Without a body-size cap, an attacker streams a multi-gigabyte body and you buffer all of it into process memory — a payload-bomb DoS that needs no cleverness, just a slow upload. Thelimitis the difference between a413and an OOM. - Guard prototype pollution. A JSON body containing
__proto__orconstructor.prototypekeys can, with a naïve merge, poisonObject.prototypeand corrupt unrelated code paths. Use a parser/merge that ignores those keys, or validate to a strict schema (your DTO layer — the patient/encounter/claim schemas) before any merge. - Check content-type. Don't
JSON.parsea body the client labeledtext/plainand didn't promise to be JSON.
Security middleware are first-class, early links. helmet (safe response headers), cors (origin policy), and the rate limiter belong near the front of the array, before expensive auth/DB work. Placing the rate limiter early is a design decision: load shedding only protects you if it happens before the resources you're protecting are touched. A rate limiter behind auth protects nothing the attacker was going to exhaust.
Every middleware runs on every matching request, on the single event loop. This is the scale fact that makes Express's concurrency model unforgiving. As you've already seen, there is one thread running the pipeline. A synchronous-heavy middleware — synchronous crypto, a JSON.parse of a huge body, a route regex with catastrophic backtracking — blocks every other in-flight request while it runs, because nothing else can execute on that thread until it yields. Catastrophic backtracking is a regex that, on a maliciously crafted input string, takes seconds or minutes to run because it tries exponentially many ways to match — that's the ReDoS attack, and on a single event loop one such request freezes everyone's. The hot path must stay async and cheap. A single bcrypt-in-a-loop or a pathological path-to-regexp pattern can flatline throughput for every patient and provider hitting the service.
The error handler is a DoS chokepoint. Under attack, every request flows through the error mapper. If it does synchronous work — synchronous logging, a blocking serialize, a sync stack-trace formatter — errors amplify latency exactly when you can least afford it. Keep the error path async and cheap; log asynchronously; don't compute expensive diagnostics inline on the request thread.
Don't leak existence through timing or status. Tying response timing to an auth result (fast reject for unknown user, slow reject for wrong password) lets an attacker enumerate accounts by stopwatch. And the 404-vs-403 decision is enforced here, in the error mapper — deciding once whether "this patient exists but you may not see them" returns 404 (hide existence) or 403 (be honest). In a PHI system this is a disclosure control, not a nicety: a 403 on a patient lookup silently confirms the record exists, which can itself be a HIPAA-relevant leak. This ties middleware ordering and error shaping directly to Chapter 31 and Chapter 32; we set the seams correctly here and develop the attacks there.
🔑 The pipeline is the trust boundary, made executable. The trust-boundary membrane from the book's opening — claims in, rulings out — is, concretely, this array of middleware. Authentication is where a claim of identity becomes verified; validation is where untrusted bytes become a typed value; the error mapper is where an internal failure becomes a safe ruling. Get the order of those links right and the membrane holds; get it wrong and a claim walks straight through to durable state — a chart, a claim, an order. Security in Express is mostly "did we run the membrane in the right order, or did we let input reach the handler before we checked it?"
9. Interview lens & exercises
Interview questions
Express questions separate "I've used app.get" from "I understand the dispatch loop." The tell is whether the answer reasons about the array, the baton, and the two lanes — or recites API names.
"Walk me through what happens to a request from socket to response in Express."
- Junior answer: "It hits the route handler and sends a response." True and empty.
- Senior answer: narrates the array — "Node parses the socket into
IncomingMessage/ServerResponse; Express walks an ordered stack via anextbaton that's really a closure over an index; each middleware handles-and-ends, mutates-and-calls-next, or fails forward withnext(err); errors switch to a second lane that skips every normal link and scans forward for a 4-arg handler; and the whole thing must terminate in exactly one response or it hangs." The signal is the mechanism, not the vocabulary.
"Why does a thrown error inside an async route handler not get caught by your error middleware in Express 4?"
- Junior: "Wrap it in try/catch" — correct fix, no understanding.
- Senior: "The
asyncfunction returns a Promise synchronously at the firstawait, before it rejects. Express doesn'tawaityour handler, so it never sees the rejection — it becomes anunhandledRejection,next(err)never fires, and the request hangs. Fix it with a wrapper that attaches.catch(next), or use Express 5's native forwarding, which couldn't be done in 4 without breaking the callback contract." Explains why, names the version boundary.
"Your error-handling middleware isn't running — what are the likely causes?"
- Junior: "The error handler is broken."
- Senior: "Three usual suspects: wrong arity — it's declared with three params, so Express treats it as normal middleware; registered before the routes, so the error lane never reaches it; or someone already sent a response, so it's a
HEADERS_SENTsituation. I'd check the parameter count first." Names the arity trap specifically.
"When would you reach for Nest over Express, and what specifically does Express stop giving you?"
- Junior: "Nest is newer and more structured."
- Senior: "Express stops giving you a container — so DI, lifecycle ownership, and shared providers are hand-wired and drift; it has no built-in async-error safety, validation pipeline, or module boundaries; and its single-pass
nextcan't express around-advice cleanly. Nest names those slots (guards, pipes, interceptors, filters) over the same pipeline and adds a container. The cost is magic, boot time, and a learning surface — so for a small service I'd stay on Express." Names the specific missing capabilities and the cost.
"How does middleware ordering become a security control?"
- Junior: "Order doesn't really matter as long as everything runs."
- Senior: "The order is the control: rate-limit → authenticate → authorize → validate → handle. Doing expensive or trusting work before auth — validating a hostile body, hitting the DB, leaking whether a patient record exists through error messages — is a vulnerability, and a rate limiter behind auth protects nothing. Misordering the array ships a vuln no correct handler code can fix." Treats the array as executable security policy.
Exercises & the Pulsely increment
Do these in a real repo; the bugs are invisible until you trigger them.
-
Build
tinyexpress(~60 lines). Implementuse/get/postand an index-drivendispatchwith a workingnext(err)that forwards to 4-arg handlers by scanning forfn.length === 4. Prove it by porting one Pulsely route (GET /encounters/:id) onto it, params and all. You haven't understood Express until your toy version routes and error-forwards. -
Pulsely increment — the full ordered stack. Reimplement Pulsely's HTTP surface (
patients,encounters,appointment slots,orders,worklist) on Express with the canonical order from §5: request-id → security headers → cors → rate-limit → logger → body-parse(limit) →/apirouter(auth → per-route validate → handler) → 404 fallthrough → single 4-arg error mapper. Use one reusableasyncHandleron every async handler, and route every error through the mapper (forbid ad-hocres.json({error})). -
Make the async-error bug visible, then fix it twice. Write a
supertesttest that hits an async handler which throws (say, an order handler whose eligibility check rejects), and assert it returns a status (not a timeout). Watch it fail (hang) with a naked async handler. Make it pass two ways — theasyncHandlerwrapper, then Express 5 native forwarding — and write a sentence on why each works. This converts an invisible production hang into a red build. -
Turn ordering invariants into regression tests. Deliberately misorder the stack — auth after validation, error handler before the routes — and write a test that catches each misordering (e.g., "an unauthenticated
POST /api/ordersreturns401, and validation never ran"). You're encoding §3's order invariant as executable guardrails so a future refactor can't silently reintroduce the vuln.
Key takeaways
- Express is an ordered array of functions sharing a mutable
(req, res)pair, each handed anextbaton — a chain of responsibility, not magic. The dispatch loop is ~60 lines you can write yourself. nextis a closure over an index, not a keyword. Calling it advances and invokes the next layer; calling it twice runs the rest twice; not calling it hangs the request. The invariants are mechanics, not rules.- The array has two lanes: normal (
next()) and error (next(err)), and Express tells them apart by arity — 4-arg(err, req, res, next)is the only thing the error lane will run. Drop thenextto please a linter and your error handler silently dies. - The async-error gotcha: an
asynchandler returns a Promise before it rejects; Express 4 doesn'tawaitit, so the rejection orphans and the request hangs with no log. Fix with anasyncHandlerwrapper (.catch(next)) or Express 5's native forwarding. - Order is semantics. Body-parse before consumers; logger first to time everything; rate-limit → authenticate → authorize → validate → handle — and that order is a security control, not a style choice. Misordering the array ships vulnerabilities.
- One error-mapping chokepoint turns domain errors into HTTP status + problem+json, keeps stack traces out of client responses, and gets the 4xx/5xx split right — the same principle as Spring's
@ControllerAdvice. - The size
limiton the body parser, security headers, and the single-event-loop cost of every middleware are first-class concerns: a missinglimitis a DoS, a sync-heavy middleware flatlines all concurrency. - Where Express stops helping — hand-wired DI, no built-in async safety, no lifecycle hooks, a single-pass
nextthat can't express around-advice — is exactly the pain that justifies Nest. Nest names the slots in this pipeline; it doesn't replace it. Learn the engine first.
← Previous: Ch 12 — Beyond REST · Up: Part III overview · Master TOC · Next: Ch 14 — NestJS, DI & Application Architecture →