Koa Body Parser
koa-bodyparser is a middleware for Koa.js that parses incoming request bodies, making them available on `ctx.request.body`. It supports JSON, URL-encoded forms, and plain text body types. The package is built upon `co-body` for parsing logic. The current stable version is `6.1.0`. Releases occur somewhat irregularly but are actively maintained, with significant updates in major versions (e.g., v6.0.0, v6.1.0). A key differentiator is its focus on structured body parsing, explicitly *not* supporting multipart form data (for which `@koa/multer` is recommended). It offers configurable limits for various body types, strict JSON parsing, and custom error handling, providing a foundational component for handling diverse client-side requests in Koa applications.
Common errors
-
HTTP 413 Payload Too Large
cause The request body size exceeded the configured limit for its content type.fixIncrease `jsonLimit`, `formLimit`, `textLimit`, or `xmlLimit` options in the `bodyParser` middleware or ensure client requests adhere to limits. Example: `bodyParser({ jsonLimit: '5mb' })`. -
Error: body parse error
cause The request body was malformed for the specified `Content-Type`, or the `onerror` option caught a parsing error.fixCheck the `Content-Type` header matches the actual body format (e.g., `application/json` for JSON). Review the client-side data being sent. Implement custom `onerror` to log details: `bodyParser({ onerror: (err, ctx) => { console.error('Parsing failed:', err); ctx.throw(422, 'Invalid body format'); } })`. -
Cannot read property 'body' of undefined
cause Attempting to access `ctx.request.body` before `koa-bodyparser` has been applied or for a request method that typically doesn't have a body (GET, HEAD, DELETE) and no body was sent.fixEnsure `app.use(bodyParser());` is called *before* any route handlers that access `ctx.request.body`. Remember that GET/HEAD/DELETE requests typically don't have bodies; `ctx.request.body` will be an empty object if no body was parsed. Also, `parsedMethods` option (if using `@koa/bodyparser`) can restrict which methods are parsed. -
TypeError: app.use() requires a middleware function but got a undefined
cause The `bodyParser` function was not called when passed to `app.use()`, or there was an issue with the import.fixEnsure `bodyParser` is called as a function: `app.use(bodyParser());`. If using CommonJS, verify `const bodyParser = require('koa-bodyparser');`.
Warnings
- breaking Starting with `v6.1.0`, the TypeScript type for `Koa.Request.body` changed from `any` to `unknown`. This change enhances type safety but may require existing TypeScript applications to add type assertions or narrow the type of `ctx.request.body`.
- breaking For Koa v1.x applications, `koa-bodyparser` v3.x and newer are not compatible. You must use `koa-bodyparser@2.x` to maintain compatibility with Koa v1.x.
- gotcha This module explicitly does *not* support parsing `multipart/form-data` (file uploads). Attempting to use it for multipart data will result in incorrect parsing or errors.
- gotcha By default, `koa-bodyparser` will only parse `json` and `form` body types. If you need to parse `text` or `xml` bodies, you must explicitly enable them using the `enableTypes` option.
- gotcha Body size limits (`jsonLimit`, `formLimit`, `textLimit`, `xmlLimit`) can lead to HTTP 413 (Payload Too Large) errors if the incoming body exceeds the configured limits. Defaults are `1mb` for JSON/text/XML and `56kb` for URL-encoded forms.
Install
-
npm install koa-bodyparser -
yarn add koa-bodyparser -
pnpm add koa-bodyparser
Imports
- bodyParser
const bodyParser = require('koa-bodyparser');import bodyParser from 'koa-bodyparser';
- bodyParser.Options
import type { Options } from 'koa-bodyparser'; - bodyParser middleware
app.use(bodyParser);
app.use(bodyParser());
Quickstart
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';
const app = new Koa();
// Apply the body parser middleware globally
app.use(bodyParser({
jsonLimit: '5mb',
formLimit: '10mb',
textLimit: '2mb',
onerror: (err, ctx) => {
console.error('Body parse error:', err);
ctx.throw(422, 'Cannot parse request body. Ensure correct Content-Type and format.');
}
}));
app.use(async ctx => {
if (ctx.method === 'POST' || ctx.method === 'PUT' || ctx.method === 'PATCH') {
// The parsed body is available at ctx.request.body
// If no body was parsed (e.g., GET request), it will be an empty object {}
console.log('Received body:', ctx.request.body);
ctx.status = 200;
ctx.body = { received: ctx.request.body };
} else {
ctx.body = 'Send a POST, PUT, or PATCH request with a body.';
}
});
const port = process.env.PORT ?? 3000;
app.listen(port, () => {
console.log(`Server listening on http://localhost:${port}`);
});