ctx.state

A plain object recommended for passing data between middleware and to views within a single request lifecycle.

Since Koa 2 Spec ↗

Syntax

ctx.state

Returns

object — A mutable plain object scoped to the current request.

Examples

import Koa from 'koa';

const app = new Koa();

// Auth middleware sets ctx.state.user
app.use(async (ctx, next) => {
  const token = ctx.get('Authorization').replace('Bearer ', '');
  ctx.state.user = await verifyJwt(token);
  await next();
});

app.use(async (ctx) => {
  ctx.body = { hello: ctx.state.user.name };
});

app.listen(3000);
Output
{"hello":"Alice"}

Notes

`ctx.state` is the idiomatic place for request-scoped values such as the authenticated user, locale, or feature flags. It is separate from `app.context` (shared across all requests) and from `ctx` itself (which may have future property collisions). Template engines like `koa-views` merge `ctx.state` into the render context automatically.

See also