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.
npm install koa-bodyparserVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate koa-bodyparser into a Koa application to parse incoming JSON and form-encoded request bodies, and how to access the parsed data on `ctx.request.body`.
Update TypeScript code to handle `unknown` type for `ctx.request.body` explicitly, e.g., `(ctx.request.body as { someField: string }).someField` or `if (typeof ctx.request.body === 'object' && ctx.request.body !== null) { /* type narrowing */ }`.For Koa v1.x, install `npm install koa-bodyparser@2 --save`. For Koa v2+, use the latest version.
For `multipart/form-data`, use a dedicated middleware like `@koa/multer` or `koa-body` (not `koa-bodyparser`).
Configure `enableTypes`: `app.use(bodyParser({ enableTypes: ['json', 'form', 'text', 'xml'] }));`Adjust limits in options: `app.use(bodyParser({ jsonLimit: '10mb', formLimit: '5mb' }));`. Inform users of potential size constraints.Increase `jsonLimit`, `formLimit`, `textLimit`, or `xmlLimit` options in the `bodyParser` middleware or ensure client requests adhere to limits. Example: `bodyParser({ jsonLimit: '5mb' })`.Check 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'); } })`.Ensure `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.
Ensure `bodyParser` is called as a function: `app.use(bodyParser());`. If using CommonJS, verify `const bodyParser = require('koa-bodyparser');`.