ctx

The Koa context object that encapsulates both the Node.js `request` and `response` objects for the current HTTP request.

Since Koa 2 Spec ↗

Syntax

app.use(async (ctx, next) => { ... })

Parameters

NameTypeRequiredDescription
ctx Context Yes A per-request object combining `ctx.request` (Koa Request), `ctx.response` (Koa Response), `ctx.req` (Node.js IncomingMessage), and `ctx.res` (Node.js ServerResponse). Many properties are aliased directly on `ctx`.
next AsyncFunction No Async function that invokes the next middleware in the stack. Always `await next()` if you want downstream middleware to run.

Returns

void — Middleware functions do not return meaningful values; respond via ctx.body.

Examples

import Koa from 'koa';

const app = new Koa();

app.use(async (ctx, next) => {
  console.log(`→ ${ctx.method} ${ctx.url}`);
  await next();
  console.log(`← ${ctx.status}`);
});

app.use(async (ctx) => {
  ctx.body = { message: 'Hello' };
});

app.listen(3000);
Output
→ GET /
← 200
// Accessing request and response via ctx aliases
app.use(async (ctx) => {
  const lang = ctx.get('Accept-Language'); // request header
  ctx.set('X-Lang', lang);                 // response header
  ctx.status = 200;
  ctx.body = 'ok';
});
Output
X-Lang: en-US,en;q=0.9

Notes

`ctx` delegates many properties directly from `ctx.request` and `ctx.response` for convenience (e.g. `ctx.body` → `ctx.response.body`, `ctx.method` → `ctx.request.method`). Use `ctx.state` to pass data between middleware and never attach ad-hoc properties directly to `ctx` to avoid collisions with future Koa properties.

See also