koa-bodyparser
Parses JSON, form-urlencoded, and text request bodies and populates `ctx.request.body`.
Syntax
import bodyParser from 'koa-bodyparser';
app.use(bodyParser([options]));
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
options | object | No | Configuration: `enableTypes` (default `['json', 'form']`), `limit` (body size limit, default `'1mb'`), `strict` (JSON strict mode), `onerror` (custom error handler function). |
Returns
function — Koa middleware that parses the request body and sets `ctx.request.body`.
Throws
HttpError— The body exceeds the `limit` or is malformed JSON (status 400/413 depending on onerror).
Examples
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
import Router from '@koa/router';
const app = new Koa();
const router = new Router();
app.use(bodyParser());
router.post('/users', async (ctx) => {
const { name, email } = ctx.request.body;
ctx.status = 201;
ctx.body = { name, email };
});
app.use(router.routes());
app.listen(3000);
Output
POST /users {"name":"Alice","email":"a@example.com"}
→ 201 {"name":"Alice","email":"a@example.com"}
// Limit body size and allow xml
app.use(bodyParser({
enableTypes: ['json', 'form', 'text'],
limit: '500kb',
}));
Output
(413 Payload Too Large if body > 500kb)
Notes
`ctx.request.body` is `{}` (not `undefined`) when parsing succeeds with
no data. For multipart/form-data (file uploads), use a separate package
such as `@koa/multer`. Mount `bodyParser()` early in the middleware stack,
before route handlers.