Middleware
Middleware is a chain of functions that each receive a request context and a next callback (or a wrapped handler). Express, Koa, and Redux use this pipeline to add logging, auth, and parsing without editing the core handler.
Detailed Explanation
A single route function that parses JSON, checks a token, writes a log, and then runs business logic is a blob. Middleware splits those steps. Each piece can run, call next(), or end the chain by sending a response.
Express style: (req, res, next) => { ... next(); }. Error middleware is (err, req, res, next). Order is registration order. If you forget next(), the request hangs. If you next() after res.end(), you double-send.
Koa / onion style: async (ctx, next) => { await next(); } lets you run code after inner handlers (timing, logging status). That is a stack of decorators, not a one-way pipe.
Redux middleware is (store) => (next) => (action) => next(action). Same idea: each layer can inspect, rewrite, or swallow the action.
In the browser, fetch wrappers and service-worker fetch events are middleware for HTTP. You do not need Express to use the pattern: an array of functions plus a runner is enough.
What it costs you: implicit order and debugging. A bug is "which layer ate the request?". Too many layers make a 10-line handler into a 12-file stack. Error paths must be designed: one layer throws, who catches?
Reach for middleware when many routes share the same prelude or epilogue. Reach for a decorator on one function when only that function needs the extra behaviour. Reach for a facade when you want a simpler API, not a pipeline.
Testing middleware is easier when next is a spy and ctx is a plain object. Assert that a failing auth layer never called next, and that a logging layer called it once. Integration tests that boot the whole app are for order and header wiring, not for every branch.
Framework middleware (Express app.use) and your own runner should share the same rule: one response per request. Two res.json calls are a crash in production and a flake in tests.
Code Examples
function run(stack, ctx) {
let i = 0;
function next() {
const fn = stack[i];
i += 1;
if (fn) return fn(ctx, next);
return undefined;
}
return next();
}
const stack = [
(ctx, next) => {
ctx.log = [];
ctx.log.push("auth");
next();
},
(ctx) => {
ctx.log.push("handler");
ctx.body = "ok";
},
];
const ctx = {};
run(stack, ctx);
console.log(ctx.body, ctx.log); // => ok [ 'auth', 'handler' ]async function onion(stack, ctx) {
let i = -1;
async function next() {
i += 1;
if (stack[i]) await stack[i](ctx, next);
}
await next();
}
const timed = async (ctx, next) => {
const t = Date.now();
await next();
ctx.ms = Date.now() - t;
};Common Gotchas
Forgetting `next()` hangs the request
every non-terminal layer must call it or send a response.
Calling `next()` twice (or after sending) is a defect
guard with a `called` flag in your runner.
Order is behaviour
auth after the handler is a security bug, not a style issue.
Onion middleware can run after the handler
put cleanup and timing in the lines after `await next()`.