app.use()
Adds a middleware function (or async generator) to the application middleware stack.
Syntax
app.use(fn) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
fn | function | AsyncFunction | Yes | An async middleware function with signature `async (ctx, next) => {}`. Call `await next()` to pass control to the next middleware. |
Returns
Application — The app instance, enabling chaining.
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
app.use(async (ctx) => {
ctx.body = 'Hello, Koa!';
});
app.listen(3000);
Output
GET / → 200 "Hello, Koa!" with header X-Response-Time: 1ms
// Conditional middleware
app.use(async (ctx, next) => {
if (ctx.path.startsWith('/api')) {
ctx.set('Content-Type', 'application/json');
}
await next();
});
Output
GET /api/users → Content-Type: application/json
Notes
Middleware is executed in the order it is added (onion model): the first
middleware added is the outermost layer. Always `await next()` unless you
intend to short-circuit. Koa does not support Express-style `(err, ctx, next)`
error middleware; use `app.on('error', handler)` or try/catch instead.