The Analogy: The Airport Passenger Pipeline
Picture a departing passenger walking into an airport terminal. They do not go straight to the aircraft. Instead they are funneled through a fixed line of stations bolted to the floor in a set order: the check-in counter, then the bag-drop belt, then the ID podium, then the security scanner, and only then the departure gate. Each station is staffed by an agent who performs exactly one job and then physically waves the passenger toward the next station down the line.
That wave is the whole trick. An agent who is satisfied with you lifts the rope and says "move along" and only then do you advance to the next desk. The layout is one-directional and the order is fixed by where the desks are bolted to the ground: you cannot reach the gate without first clearing check-in, then bag drop, then the ID podium, in that sequence. Nobody teleports to the gate; everybody walks the same corridor in the same order.
A station is also allowed to stop you cold. The ID podium can decide your document is invalid, hand you a printed rejection slip, and turn you around on the spot. When that happens you never see the scanner or the gate at all; the line simply ends for you there. Some stations are not on the main corridor either: a VIP lounge desk sits only in the premium wing, so it processes just the travelers routed down that particular hallway and no one else.
Now imagine one agent breaks the rhythm. The bag-drop clerk takes your suitcase, weighs it, prints the tag, and then gets distracted and never lifts the rope. You are not rejected and you are not passed along; you just stand at the belt indefinitely while the line behind you grows and grows. The whole pipeline seizes on that single silent station. This is the exact failure of a middleware function that neither ends the response nor calls next(): the request hangs until it times out, and every client waiting behind it is stuck too.
Syntax or Core Structure
In Express, middleware is simply a function that sits in the request-response pipeline and receives three arguments: the request object (req), the response object (res), and a callback conventionally named next. The function may inspect or modify req and res, it may end the exchange by sending a response, or it may call next() to hand control to the next function in line. Those are the only three outcomes, and choosing exactly one of them is the entire contract.
The Middleware Signature
function stationAgent(req, res, next) {
// 1. do some work (read a header, attach a value, log something)
req.checkedIn = true;
// 2. THEN pick exactly one of these:
// a) call next() to pass control onward
next();
// b) or end the cycle: res.send(...) / res.json(...) / res.end()
// c) or reject: res.status(401).json({ error: 'stopped here' })
}
Registering Middleware
You attach middleware to the application with app.use(). With no path it runs for every incoming request; with a path prefix it runs only for requests whose URL starts with that prefix. Route handlers such as app.get() are themselves the final middleware in the chain.
const express = require('express');
const app = express();
app.use(stationAgent); // global: runs for every request
app.use('/vip', vipLoungeAgent); // mounted: runs only under /vip
app.get('/gate', gateHandler); // the terminal handler
A Minimal Tagging Middleware
The smallest useful middleware attaches a value to req and waves the request onward. Here one global function stamps req.stage, and the route handler reads it back:
const express = require('express');
const app = express();
app.use(function (req, res, next) {
req.stage = 'tagged';
next();
});
app.get('/whoami', function (req, res) {
res.json({ stage: req.stage, path: req.path });
});
app.listen(4103, function () {
console.log('mw_basic listening on port 4103');
});
A request to /whoami passes through the tagging middleware first, which sets req.stage, then reaches the handler which serializes it:
Output:
{"stage":"tagged","path":"/whoami"} [200]
The trailing [200] is the HTTP status code, printed by the curl command used to probe the server; the JSON object before it is the response body.
Technical Depth: The Five Kinds and the Order They Run
The Five Kinds of Middleware
Express recognizes five categories of middleware. They differ in how they are attached and, in one case, in how many arguments the function takes.
| Kind | How it is attached | Notes |
|---|---|---|
| Application-level | app.use(fn) or app.METHOD | Runs for the whole app or a mounted path |
| Router-level | router.use(fn) on a Router | Same idea, scoped to one Router instance |
| Error-handling | app.use(fn) with four args | Signature is (err, req, res, next) |
| Built-in | express.json(), express.static | Ships inside Express itself |
| Third-party | app.use(cors()), app.use(morgan) | Installed from npm and mounted |
The error-handling kind is the odd one out: Express detects it purely by counting parameters. A function declared with four arguments is treated as an error handler and is skipped during the normal flow, only being invoked when an earlier function calls next(someError).
Execution Order Is Registration Order
Middleware runs in the order it is registered, top to bottom. A global app.use runs for every path; a mounted app.use('/vip', ...) runs only when the URL begins with that prefix. This program records each station it passes into an array on req:
const express = require('express');
const app = express();
app.use(function (req, res, next) {
req.trail = ['check-in'];
next();
});
app.use(function (req, res, next) {
req.trail.push('bag-drop');
next();
});
app.use('/vip', function (req, res, next) {
req.trail.push('vip-lounge');
next();
});
app.get('/gate', function (req, res) {
res.json({ trail: req.trail });
});
app.get('/vip/gate', function (req, res) {
res.json({ trail: req.trail });
});
app.listen(4105, function () {
console.log('order listening on port 4105');
});
A request to /gate clears the two global stations only, because its URL does not start with /vip:
Output:
{"trail":["check-in","bag-drop"]} [200]
A request to /vip/gate clears the same two global stations and then the mounted VIP station, because its URL does start with /vip:
Output:
{"trail":["check-in","bag-drop","vip-lounge"]} [200]
The difference between the two responses is produced entirely by the path prefix on the third app.use. Nothing about the handlers changed; only which stations the URL was eligible to visit.
What next() Carries
The argument you pass to next changes what happens next, and this is the most misunderstood part of the API.
| Call | Effect |
|---|---|
| next() | Advance to the next matching middleware or route |
| next('route') | Skip the rest of this route stack, try the next route |
| next(err) | Jump straight to error-handling middleware |
Passing any value other than the string 'route' is interpreted as an error and short-circuits the normal pipeline. That is why a stray next(somethingTruthy) can make a request mysteriously land in your error handler.
Real World Example: A Boarding Pipeline for a Gate API
The following server models the airport analogy directly. Two application-level middleware functions run before the /gate handler. The first is a counter that stamps every arriving request with a sequential ticket number. The second is a guard that refuses to wave the request onward unless it carries an x-pass header, mirroring the ID podium that turns away anyone without valid documents.
const express = require('express');
const app = express();
let counter = 0;
app.use(function (req, res, next) {
counter = counter + 1;
req.ticket = counter;
next();
});
app.use(function (req, res, next) {
if (!req.headers['x-pass']) {
return res.status(401).json({ ticket: req.ticket, error: 'no boarding pass' });
}
req.passenger = req.headers['x-pass'];
next();
});
app.get('/gate', function (req, res) {
res.json({ ticket: req.ticket, passenger: req.passenger, boarded: true });
});
app.listen(4104, function () {
console.log('pipeline listening on port 4104');
});
Notice the two ways the guard behaves. When the header is missing it calls res.status(401).json(...) and pointedly does NOT call next(); this is the rejection slip, ending the cycle before the gate handler ever runs. When the header is present it attaches req.passenger and calls next(), the wave-through that lets the gate handler complete the boarding.
A first request with no header is stamped ticket 1 by the counter, then bounced by the guard with a 401:
Output:
{"ticket":1,"error":"no boarding pass"} [401]
The next request carries x-pass: ada. It is stamped ticket 2, cleared by the guard, and reaches the gate:
Output:
{"ticket":2,"passenger":"ada","boarded":true} [200]
A third request with x-pass: grace is stamped ticket 3 and boards the same way:
Output:
{"ticket":3,"passenger":"grace","boarded":true} [200]
This program is instructive precisely because it has real flaws worth naming. The counter lives in a single module-level variable, which means it is process-global mutable state: run two copies of this server behind a load balancer and each keeps its own counter, so ticket numbers collide and are no longer unique. The guard treats the raw x-pass header as a trusted identity, but a header is trivially spoofable by any client, so this is authentication in name only. The 401 response echoes the internal ticket number back to an unauthenticated caller, leaking a small piece of server state to strangers. And the guard accepts any non-empty string as a valid pass, performing no format check, no signature check, and no expiry check, all of which a real boarding system would demand.
Common Mistakes
- Forgetting to call next(). A middleware that neither ends the response nor calls
next()leaves the request hanging until it times out. This is the silent bag-drop clerk from the analogy, and it is the single most common middleware bug.
- Calling next() and also sending a response. If you call
res.json(...)and then also callnext(), control continues down the chain and a later handler may try to send a second response, producing the "Cannot set headers after they are sent" error.
- Registering middleware after the route it should protect. Because order is registration order, an
app.useplaced belowapp.get('/gate', ...)never runs for that route. Guards must be registered before the handlers they guard.
- Putting slow or blocking work in a global middleware. Middleware mounted with a bare
app.useruns on every single request, including health checks and static assets. Expensive work there taxes the entire application, not just the routes that need it.
- Assuming a four-argument function is a normal middleware. Express counts parameters: any function with four arguments is treated as an error handler and is skipped in the normal flow. Adding an unused fourth parameter silently removes the function from the main pipeline.
- Mutating shared module state per request. Storing per-request data in a module-level variable instead of on
reqcauses requests to clobber each other under concurrency. Per-request data belongs on thereqobject, which is unique to each exchange.
- Trusting the order of asynchronous work inside middleware. Calling
next()before an asynchronous operation finishes lets the pipeline advance while the work is still pending, so the handler may run before the data it depends on exists.
- Mounting a path-specific middleware globally by mistake. Writing
app.use(vipOnly)instead ofapp.use('/vip', vipOnly)applies the check to every route, not just the intended wing, often locking users out of pages that should be open.
- Swallowing errors instead of forwarding them. Catching an error inside middleware and neither responding nor calling
next(err)strands the request. Errors that cannot be handled locally should be passed tonext(err)so the error-handling middleware can respond.
Best Practices
- Give every middleware exactly one job. A function that authenticates, logs, and parses at once is hard to reorder and test. Small single-purpose functions compose into a readable pipeline, just as each airport desk performs one task.
- Order the pipeline deliberately, cheapest and most selective first. Register fast rejections such as authentication and validation before expensive work, so bad requests are turned away before they cost anything. Placement is behavior in Express.
- Attach per-request data to req, never to module scope. Use
req.user,req.ticket, and similar properties so each request carries its own state and concurrent requests never interfere with one another.
- Always terminate every path: respond or call next(). Audit each branch of a middleware to be sure it either sends a response or calls
next(). A branch that does neither is a latent hang.
- Mount narrowly with a path prefix when a check is route-specific. Prefer
app.use('/admin', guard)over a global guard plus internal path checks; the router should express where the middleware applies.
- Centralize error handling in a single four-argument handler. Forward failures with
next(err)and let one error-handling middleware at the bottom of the stack format the response, rather than duplicating error formatting everywhere.
- Prefer well-maintained built-in and third-party middleware over hand-rolled versions. Use
express.json()for body parsing and vetted packages for CORS, logging, and security headers instead of reimplementing them and inheriting their edge-case bugs.
- Return early when you end the cycle. Write
return res.status(401).json(...)so execution stops at the rejection and cannot accidentally fall through into a laternext()call in the same function.
Practice Exercises
- Build a request timer. Write a global middleware that records the time when a request arrives and, after the handler runs, computes how long it took. Since middleware runs top to bottom, think about where the start and end measurements must be registered for the timing to include the whole pipeline.
- Add a role gate on a mounted path. Create an
/adminsection protected by a middleware mounted withapp.use('/admin', ...)that requires anx-roleheader equal toadmin, returning 403 otherwise. Verify that routes outside/adminremain reachable without the header.
- Chain three named middleware on one route. Register three separate functions on a single route so that the request visits them in a known order, each pushing its name onto an array on
req, and have the handler return that array. Predict the array before running it, then confirm.
- Introduce and then fix a hanging route. Deliberately write a middleware that omits
next()and observe the request hang, then fix it. Explain in a comment which of the three legal outcomes (respond, next, or reject) the broken version failed to reach.