Koa Compose Middleware Pipeline Order
Compose Koa middleware functions in explicit execution order, tracing the onion model pass-through with early termination and downstream control.
Code
import Koa from 'koa';
import compose from 'koa-compose';
async function timing(ctx, next) {
const started = Date.now();
await next();
ctx.set('x-response-time', String(Date.now() - started));
}
async function guard(ctx, next) {
if (ctx.path === '/internal') {
ctx.status = 403;
return; // early termination: downstream never runs
}
await next();
}
async function body(ctx) {
ctx.body = { ok: true };
}
const app = new Koa();
app.use(compose([timing, guard, body]));
const pipeline = compose([timing, guard, body]);
const ctx = app.createContext(null, null);
await pipeline(ctx, () => Promise.resolve());
console.log('composed response headers:', ctx.response.status);Report a problem with this exampleOpens a pre-filled issue on GitHub.