ctx.request.length
The `Content-Length` of the request body in bytes, parsed as an integer.
Syntax
ctx.request.length Returns
number | undefined — Content-Length in bytes, or `undefined` if the header is absent.
Examples
import Koa from 'koa';
const app = new Koa();
const MAX_BODY = 1_000_000; // 1 MB
app.use(async (ctx, next) => {
if (ctx.request.length && ctx.request.length > MAX_BODY) {
ctx.throw(413, 'Payload Too Large');
}
await next();
});
app.use(async (ctx) => {
ctx.body = 'ok';
});
app.listen(3000);
Output
POST with 2 MB body → 413 Payload Too Large
Notes
Returns `undefined` when the `Content-Length` header is absent (e.g.
chunked transfer encoding). For reliable body size limiting, also
configure the limit option in `koa-bodyparser` which handles chunked
requests.