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);What the code does
Koa Compose Middleware Pipeline Order is built around the functions timing, guard and body.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
What to watch for
koaandkoa-composemust be installed first — the snippet imports them directly.
Applying it
The main signature reads async function timing(ctx, next)
The run emits 1 labeled section — composed response headers: — one per step.
Statements that matter
await pipeline(ctx, () => Promise.resolve());
await next();
Interactive Tools for This Topic
Docker Run to Compose ConverterTransform docker run CLI commands with ports, environment variables, volumes, networks, and resource limits into clean compose.yaml service definitions.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Are there third-party dependencies?
- `koa` and `koa-compose` — install them with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.