ctx.assert()

Throws an HTTP error when the given value is falsy, similar to Node's `assert` but for HTTP responses.

Since Koa 2 Spec ↗

Syntax

ctx.assert(value, [status], [message], [properties])

Parameters

NameTypeRequiredDescription
value any Yes The value to test. If falsy (`null`, `undefined`, `0`, `false`, `""`), an HTTP error is thrown.
status number No HTTP status code to use. Defaults to `500`.
message string No Error message sent to the client (exposed for 4xx by default).
properties object No Extra properties merged onto the error (same as `ctx.throw`).

Returns

void — Returns normally when `value` is truthy; throws otherwise.

Throws

  • HttpError — The provided value is falsy.

Examples

import Koa from 'koa';

const app = new Koa();

app.use(async (ctx) => {
  const { id } = ctx.query;
  ctx.assert(id, 400, 'Missing required query param: id');

  const item = await db.findById(id);
  ctx.assert(item, 404, 'Item not found');

  ctx.body = item;
});

app.listen(3000);
Output
GET /items          → 400 Missing required query param: id
GET /items?id=999   → 404 Item not found
GET /items?id=1     → 200 { id: 1, name: "Widget" }

Notes

A concise alternative to `if (!x) ctx.throw(...)`. Internally delegates to `ctx.throw()` so error handling is identical. Prefer `ctx.assert` for guard clauses at the top of middleware to keep code readable.

See also