Registry / web-framework / koa-bodyparser

koa-bodyparser

JSON →
library4.4.1jsnpmunverified

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-bodyparser
INSTALL
IMPORT
SIG · KOA-BODYPARSER
K
koa-bodyparser
web-frameworkjavascriptv4.4.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

bodyParser
import bodyParser from 'koa-bodyparser';
const bodyParser = require('koa-bodyparser');
While CommonJS `require` is shown in older READMEs, modern Koa projects primarily use ESM `import`.
bodyParser.Options
import type { Options } from 'koa-bodyparser';
Importing types explicitly using `import type` is best practice in TypeScript.
bodyParser middleware
app.use(bodyParser());
app.use(bodyParser);
The `bodyParser` function returns a Koa middleware, so it must be called (e.g., `bodyParser()`) even without options. Passing the function directly will not initialize the middleware correctly.

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`.

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}`); });
Debug
Known issues
breakingStarting 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`.
fix
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 */ }`.
affects: >=6.1.0
breakingFor 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.
fix
For Koa v1.x, install `npm install koa-bodyparser@2 --save`. For Koa v2+, use the latest version.
affects: >=3.0.0
gotchaThis 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.
fix
For `multipart/form-data`, use a dedicated middleware like `@koa/multer` or `koa-body` (not `koa-bodyparser`).
affects: >=1.0.0
gotchaBy 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.
fix
Configure `enableTypes`: `app.use(bodyParser({ enableTypes: ['json', 'form', 'text', 'xml'] }));`
affects: >=1.0.0
gotchaBody 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.
fix
Adjust limits in options: `app.use(bodyParser({ jsonLimit: '10mb', formLimit: '5mb' }));`. Inform users of potential size constraints.
affects: >=1.0.0
Errors
Common errors & fixes
HTTP 413 Payload Too Large
The request body size exceeded the configured limit for its content type.
fix
Increase `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
The request body was malformed for the specified `Content-Type`, or the `onerror` option caught a parsing error.
fix
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'); } })`.
Cannot read property 'body' of undefined
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.
fix
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.
TypeError: app.use() requires a middleware function but got a undefined
The `bodyParser` function was not called when passed to `app.use()`, or there was an issue with the import.
fix
Ensure `bodyParser` is called as a function: `app.use(bodyParser());`. If using CommonJS, verify `const bodyParser = require('koa-bodyparser');`.
Upgrade
Version history
4.4.1latest on npm
Audit
Dependencies
koarequiredPeer dependency for Koa application context and middleware types, added in v5.1.1.
co-bodyrequiredCore dependency providing the underlying body parsing logic.
@types/cobodyoptionalTypeScript type definitions for `co-body`, fixed as a dependency in v6.0.0.
@types/koaoptionalTypeScript type definitions for Koa, essential for type-checking middleware.
Agent activity
2 hits · last 30 days
node
2
Resources
koa-bodyparser — npm install koa-bodyparser · libregistry