ctx.response.status

Gets or sets the HTTP response status code.

Since Koa 2 Spec ↗

Syntax

ctx.response.status = code  // or ctx.status = code

Parameters

NameTypeRequiredDescription
code number Yes A valid HTTP status code (e.g. `200`, `201`, `204`, `400`, `404`, `500`). Koa initialises this to `404` until `ctx.body` is set.

Returns

number — The current status code.

Throws

  • Error — An invalid HTTP status code is assigned.

Examples

import Koa from 'koa';

const app = new Koa();

app.use(async (ctx) => {
  if (ctx.method === 'POST') {
    ctx.status = 201;
    ctx.body = { id: 42, created: true };
  } else {
    ctx.status = 200;
    ctx.body = 'ok';
  }
});

app.listen(3000);
Output
POST / → 201 {"id":42,"created":true}
GET  / → 200 ok
// Respond with no body
app.use(async (ctx) => {
  ctx.status = 204; // No Content
});
Output
HTTP/1.1 204 No Content

Notes

Koa sets the status to `404` by default; assigning to `ctx.body` changes it to `200` automatically. Setting `ctx.status = 204` or `304` removes the body. Use `ctx.message` to read/write the corresponding status message.

See also