ctx.response.body
Sets the response body; Koa infers Content-Type and Content-Length automatically based on the assigned value.
Syntax
ctx.response.body = value // or ctx.body = value Parameters
| Name | Type | Required | Description |
|---|---|---|---|
value | string | Buffer | Stream | object | null | Yes | The response body. Accepted types: - `string` → `text/html` or `text/plain` - `Buffer` → `application/octet-stream` - `Stream` (Readable) → `application/octet-stream` - `object` / `Array` → `application/json` (JSON.stringify'd) - `null` → 204 No Content |
Returns
void — Setter; returns nothing.
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
if (ctx.path === '/json') {
ctx.body = { users: [{ id: 1, name: 'Alice' }] };
} else if (ctx.path === '/text') {
ctx.body = 'Plain text response';
} else {
ctx.body = null; // 204 No Content
}
});
app.listen(3000);
Output
GET /json → 200 {"users":[{"id":1,"name":"Alice"}]}
GET /text → 200 Plain text response
GET / → 204 No Content
import { createReadStream } from 'node:fs';
app.use(async (ctx) => {
ctx.type = 'application/pdf';
ctx.body = createReadStream('./report.pdf');
});
Output
GET /report → 200 (PDF binary stream)
Notes
Setting `ctx.body` to a non-null value automatically sets the status to
`200` if it was previously `404`. The Content-Type can be overridden
by setting `ctx.type` after (or before) setting `ctx.body`. For JSON,
Koa uses `JSON.stringify` — install `koa-json` for pretty-printed output.