Understanding Koa middleware: handling a request around `await next()`
Koa is a middleware framework for Node.js. For each request, it connects asynchronous middleware through a ctx object to build an HTTP response. The key is that await next() passes control downstream, then resumes the current function after downstream work finishes. This article follows the current Koa 3.x documentation to build a small server and inspect execution order and error handling.
Koa is a middleware framework for Node.js. For each request, it connects asynchronous middleware through a ctx object to build an HTTP response. The key is that await next() passes control downstream, then resumes the current function after downstream work finishes. This article follows the current Koa 3.x documentation to build a small server and inspect execution order and error handling.
Before you start
The current Koa repository README requires Node.js 18 or later. Check your runtime and installed Koa version first. Koa does not bundle extras such as a router or JSON body parser. The example routes one path directly and assumes no add-on package.
const Koa = require('koa');
const app = new Koa();
app.use(async (ctx, next) => {
const started = Date.now();
try {
await next();
} catch (err) {
ctx.status = err.status || 500;
ctx.body = { error: ctx.status === 500 ? 'Internal Server Error' : err.message };
ctx.app.emit('error', err, ctx);
}
ctx.set('X-Response-Time', `${Date.now() - started}ms`);
});
app.use(async (ctx, next) => {
if (ctx.method === 'GET' && ctx.path === '/health') {
ctx.body = { status: 'ok' };
return;
}
await next();
});
app.use(async ctx => {
ctx.status = 404;
ctx.body = { error: 'Not Found' };
});
app.on('error', (err, ctx) => {
console.error('request failed', ctx?.method, ctx?.url, err);
});
app.listen(3000);Middleware runs down and then back up
Incoming requests start middleware in app.use() registration order. When middleware calls await next(), the next function runs. Once downstream work finishes, control resumes in reverse order at each waiting call site. That is why the first middleware can set X-Response-Time after the response is prepared.
Middleware that does not call next() usually ends processing and skips everything downstream. The /health branch returns immediately when it matches; other requests continue to the 404 handler. Adding headers after response creation can fail in situations involving an already-sent stream or socket, so this example uses a small response object.
Error boundary and status
An outer error middleware can wrap await next() in try/catch to catch errors thrown downstream. If it converts an error into a response and does not rethrow it, that error does not continue through Koa's error event flow. The example explicitly emits error so it can be logged. Keep sensitive request bodies and credentials out of logs.
The example uses err.status and defaults to 500. Do not expose every error message to clients: internal details may leak. It returns a generic message for 500 responses. In production, distinguish public messages from internal failures and choose a clear policy between custom handling and Koa's default handler.
Verify the expected behavior
Save the code as app.js in a project with Koa installed, then run node app.js. A GET http://localhost:3000/health should return status 200 and {"status":"ok"}. An unknown path should return 404 and Not Found. Both responses should include X-Response-Time. These are expected results; execution was not performed here.
If the route or header is missing, check app.use() order, a missing await next(), and the request method and path. If the error middleware does not run, check whether an earlier layer caught the error and whether next() is awaited. Koa v3 removed the old Koa 1.x generator middleware signature; do not mix old examples into this stack.
Official sources
[Koa repository and installation requirements](https://github.com/koajs/koa)
[Koa middleware guide](https://github.com/koajs/koa/blob/master/docs/guide.md)
[Koa error handling](https://github.com/koajs/koa/blob/master/docs/error-handling.md)
[Koa Application API](https://github.com/koajs/koa/blob/master/docs/api/index.md)