Koa middleware is an onion: each middleware receives the context and a next function; code before await next() runs on the way in, code after it runs on the way out, once everything inside has finished. compose builds a dispatch(i) that calls middleware i with next = () => dispatch(i + 1) and returns a promise. The details that separate a real answer: always return a promise (turn synchronous throws into rejections), let errors propagate outward so an outer middleware can try/catch around await next(), reject if a middleware calls next() twice, and accept a final next so composed stacks can nest.
Implement a compose middleware function so that async middlewares like Koa-style f1, f2, f3 (each calling next()) execute in the correct nested order.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Plain compose(f, g, h)(x) means f(g(h(x))): a reduceRight over the functions. It's the idea middleware builds on: one function made out of many.
// compose(f, g, h)(x) is f(g(h(x))): functions run right to left.const compose = (...fns) => (x) => fns.reduceRight((value, fn) => fn(value), x);
passes 2 checks run on every build, against the native method where there is one
- runs right to left
- no functions: identity
Instead of passing a value along, each middleware is handed next, a function that runs the rest of the stack. Calling it in the middle splits the middleware into a before part and an after part, which gives the 1 in, 2 in, 3 in, 3 out, 2 out, 1 out order. Not calling next stops the chain (an auth check that rejects a request).
// Middleware as an onion: each one gets the context and next(); code before next() runs on the// way in, code after it on the way out.function compose(middleware) {return function run(ctx) {const dispatch = (i) => {const fn = middleware[i];if (!fn) return; // past the last one: turn aroundreturn fn(ctx, () => dispatch(i + 1));};return dispatch(0);};}
passes 3 checks run on every build, against the native method where there is one
- onion order: in, in, in, out, out, out
- a middleware can stop the chain by not calling next
- context is shared
With async middleware, await next() waits for every inner middleware to finish, so a timing middleware measures the whole request and an error middleware wraps everything with try/catch. dispatch always returns a promise: Promise.resolve(fn(...)) for values, and a synchronous throw is caught and turned into a rejection. An index of the furthest middleware reached detects next() being called twice, which would run the rest of the stack twice. The optional last function lets one composed stack be used as a middleware inside another.
// Koa-style async compose. Always returns a promise; an error anywhere rejects it, and an outer// middleware can catch an inner one's error with try/catch around `await next()`.function compose(middleware) {if (!Array.isArray(middleware)) throw new TypeError('middleware must be an array');for (const fn of middleware) if (typeof fn !== 'function') throw new TypeError('middleware must be functions');return function run(ctx, last) {let index = -1; // the furthest middleware reachedfunction dispatch(i) {if (i <= index) return Promise.reject(new Error('next() called multiple times'));index = i;const fn = i === middleware.length ? last : middleware[i]; // `last` lets composed stacks nestif (!fn) return Promise.resolve();try {return Promise.resolve(fn(ctx, () => dispatch(i + 1)));} catch (err) {return Promise.reject(err); // a synchronous throw becomes a rejection too}}return dispatch(0);};}
passes 6 checks run on every build, against the native method where there is one
- async onion: outer code after next waits for inner middleware
- timing middleware measures everything inside it
- an outer middleware catches an inner error
- sync throws become rejections; calling next twice rejects
- composed stacks nest through the last argument
- non-functions are rejected up front
Koa
Koa's whole request pipeline is this compose: logging, error handling, auth, body parsing and the router are middleware around each other, and response time is measured by the outermost one.
Redux middleware
Redux middleware (store => next => action => ...) is the same onion around dispatch, built with compose; logging and async handling (redux-thunk) sit there.
Express is different
Express middleware also calls next(), but it doesn't return a promise or wait for downstream middleware, so code after next() can't see the response. That's the difference interviewers often ask about.
Calling
next()withoutawaitorreturnin async middleware: the outer code runs before the inner middleware has finished.Letting a synchronous throw escape instead of returning a rejected promise.
No guard against
next()being called twice, so the rest of the stack runs twice.Swallowing errors inside
dispatchinstead of letting them reach the outer middleware.
How is Koa's middleware model different from Express's?
Koa middleware returns promises and await next() resumes after downstream middleware finishes, so it can run code on the way out. Express calls next() and moves on; post-processing needs res.on('finish').
How would you add a timeout to the whole stack?
An outermost middleware that races next() against a timer and sets a 503 if the timer wins (with an AbortController passed on ctx so downstream work can stop).
Why does the index check catch double next() calls?
Each dispatch(i) records the furthest index reached. A second call to the same next asks for an index that isn't beyond it, which can only happen if next was called twice.