{"id":16413,"library":"koa-bodyparser","title":"Koa Body Parser","description":"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.","status":"active","version":"4.4.1","language":"javascript","source_language":"en","source_url":"git://github.com/koajs/bodyparser","tags":["javascript","bodyParser","json","urlencoded","koa","body"],"install":[{"cmd":"npm install koa-bodyparser","lang":"bash","label":"npm"},{"cmd":"yarn add koa-bodyparser","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-bodyparser","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Peer dependency for Koa application context and middleware types, added in v5.1.1.","package":"koa","optional":false},{"reason":"Core dependency providing the underlying body parsing logic.","package":"co-body","optional":false},{"reason":"TypeScript type definitions for `co-body`, fixed as a dependency in v6.0.0.","package":"@types/cobody","optional":true},{"reason":"TypeScript type definitions for Koa, essential for type-checking middleware.","package":"@types/koa","optional":true}],"imports":[{"note":"While CommonJS `require` is shown in older READMEs, modern Koa projects primarily use ESM `import`.","wrong":"const bodyParser = require('koa-bodyparser');","symbol":"bodyParser","correct":"import bodyParser from 'koa-bodyparser';"},{"note":"Importing types explicitly using `import type` is best practice in TypeScript.","symbol":"bodyParser.Options","correct":"import type { Options } from 'koa-bodyparser';"},{"note":"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.","wrong":"app.use(bodyParser);","symbol":"bodyParser middleware","correct":"app.use(bodyParser());"}],"quickstart":{"code":"import Koa from 'koa';\nimport bodyParser from 'koa-bodyparser';\n\nconst app = new Koa();\n\n// Apply the body parser middleware globally\napp.use(bodyParser({\n  jsonLimit: '5mb',\n  formLimit: '10mb',\n  textLimit: '2mb',\n  onerror: (err, ctx) => {\n    console.error('Body parse error:', err);\n    ctx.throw(422, 'Cannot parse request body. Ensure correct Content-Type and format.');\n  }\n}));\n\napp.use(async ctx => {\n  if (ctx.method === 'POST' || ctx.method === 'PUT' || ctx.method === 'PATCH') {\n    // The parsed body is available at ctx.request.body\n    // If no body was parsed (e.g., GET request), it will be an empty object {}\n    console.log('Received body:', ctx.request.body);\n    ctx.status = 200;\n    ctx.body = { received: ctx.request.body };\n  } else {\n    ctx.body = 'Send a POST, PUT, or PATCH request with a body.';\n  }\n});\n\nconst port = process.env.PORT ?? 3000;\napp.listen(port, () => {\n  console.log(`Server listening on http://localhost:${port}`);\n});","lang":"typescript","description":"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`."},"warnings":[{"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 */ }`.","message":"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`.","severity":"breaking","affected_versions":">=6.1.0"},{"fix":"For Koa v1.x, install `npm install koa-bodyparser@2 --save`. For Koa v2+, use the latest version.","message":"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.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"For `multipart/form-data`, use a dedicated middleware like `@koa/multer` or `koa-body` (not `koa-bodyparser`).","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Configure `enableTypes`: `app.use(bodyParser({ enableTypes: ['json', 'form', 'text', 'xml'] }));`","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Adjust limits in options: `app.use(bodyParser({ jsonLimit: '10mb', formLimit: '5mb' }));`. Inform users of potential size constraints.","message":"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.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Increase `jsonLimit`, `formLimit`, `textLimit`, or `xmlLimit` options in the `bodyParser` middleware or ensure client requests adhere to limits. Example: `bodyParser({ jsonLimit: '5mb' })`.","cause":"The request body size exceeded the configured limit for its content type.","error":"HTTP 413 Payload Too Large"},{"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'); } })`.","cause":"The request body was malformed for the specified `Content-Type`, or the `onerror` option caught a parsing error.","error":"Error: body parse error"},{"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.","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.","error":"Cannot read property 'body' of undefined"},{"fix":"Ensure `bodyParser` is called as a function: `app.use(bodyParser());`. If using CommonJS, verify `const bodyParser = require('koa-bodyparser');`.","cause":"The `bodyParser` function was not called when passed to `app.use()`, or there was an issue with the import.","error":"TypeError: app.use() requires a middleware function but got a undefined"}],"ecosystem":"npm"}