ctx.response.length
Gets or sets the `Content-Length` response header in bytes.
Syntax
ctx.response.length // or ctx.length Parameters
| Name | Type | Required | Description |
|---|---|---|---|
value | number | No | When used as a setter, explicitly sets the `Content-Length` header. |
Returns
number | undefined — Content-Length in bytes, or `undefined` when not set and body length cannot be determined.
Examples
import Koa from 'koa';
const app = new Koa();
app.use(async (ctx) => {
const data = JSON.stringify({ hello: 'world' });
ctx.type = 'application/json';
ctx.length = Buffer.byteLength(data);
ctx.body = data;
});
app.listen(3000);
Output
Content-Length: 17
{"hello":"world"}
Notes
Koa automatically computes `Content-Length` for string and Buffer bodies.
Manually setting it is useful when streaming responses where the total size
is known in advance, enabling progress indicators in the client. For
streams with unknown length, omit `Content-Length` and the response will
use chunked transfer encoding.