Koa Body Parser Middleware
koa-body is a robust middleware for the Koa.js web framework designed to parse various request body types. It supports `multipart/form-data` for file uploads, `application/x-www-form-urlencoded`, and `application/json` payloads. Functionally, it offers similar capabilities to a combination of Express's `bodyParser` and `multer`. The current stable version is 7.0.1, and the project is actively maintained by the Koa community, demonstrating a healthy release cadence with recent updates in 2025. Key differentiators include its seamless integration with Koa's middleware system, comprehensive content-type support, and flexible options for patching the parsed body to Koa's context (`ctx.request.body`) or Node's native request object (`ctx.req.body`), alongside configurable limits for body and file sizes.
Common errors
-
TypeError: ctx.request.body is undefined
cause The `koa-body` middleware was not applied to the route or application, or the request method is not one of the default `POST`, `PUT`, `PATCH` methods.fixEnsure `app.use(koaBody());` is called before routes that expect a body. If expecting bodies on other HTTP methods, configure `parsedMethods` option: `koaBody({ parsedMethods: ['POST', 'GET'] })`. -
Error: request entity too large
cause The incoming request body (JSON, form, or text) exceeds the configured `jsonLimit`, `formLimit`, or `textLimit` options.fixIncrease the relevant size limit in the `koaBody` options, e.g., `koaBody({ jsonLimit: '5mb', formLimit: '2mb' });`. Defaults are `1mb` for JSON and `56kb` for form/text. -
Files are not being uploaded or ctx.request.files is empty for multipart requests.
cause The `multipart` option is not enabled in the `koaBody` configuration.fixSet `multipart: true` in the `koaBody` options: `koaBody({ multipart: true });`. Also, ensure your HTML form has `enctype="multipart/form-data"` or your API client sends the correct `Content-Type` header.
Warnings
- gotcha The v7.0.0 major version bump primarily introduced internal tooling updates, refactoring, and improved TypeScript support, rather than significant breaking API changes for most common use cases. While internal types and raw body access (`ctx.request.rawBody`) were refined, core API usage for parsing `json`, `urlencoded`, and `multipart` largely remained consistent.
- breaking `koa-body` by default only parses bodies for `POST`, `PUT`, and `PATCH` HTTP methods. Other methods like `GET`, `HEAD`, or `DELETE` will not have `ctx.request.body` populated unless explicitly configured.
- gotcha For requests with unsupported text body types (e.g., `text/xml`), the raw unparsed body is available at `ctx.request.body` directly without needing `includeUnparsed` option, provided `koa-body` is used. If `includeUnparsed` is true, it also populates `ctx.request.rawBody` for non-multipart bodies.
- gotcha File uploads (multipart bodies) are disabled by default. If you intend to handle file uploads, you must explicitly enable the `multipart` option.
Install
-
npm install koa-body -
yarn add koa-body -
pnpm add koa-body
Imports
- koaBody
import koaBody from 'koa-body';
import { koaBody } from 'koa-body'; - koaBody
const koaBody = require('koa-body');const { koaBody } = require('koa-body'); - KoaBodyMiddlewareOptions
import type { KoaBodyMiddlewareOptions } from 'koa-body';
Quickstart
import Koa from 'koa';
import { koaBody } from 'koa-body';
const app = new Koa();
// Apply koa-body middleware globally or on specific routes
app.use(koaBody({
multipart: true, // Enable multipart for file uploads
urlencoded: true,
json: true,
formLimit: '1mb', // Limit form body size
jsonLimit: '1mb', // Limit JSON body size
textLimit: '1mb' // Limit text body size
}));
app.use(async (ctx) => {
// For POST, PUT, PATCH requests, the parsed body is available at ctx.request.body
if (ctx.method === 'POST' || ctx.method === 'PUT' || ctx.method === 'PATCH') {
console.log('Request Body:', ctx.request.body);
if (ctx.request.files) {
console.log('Uploaded Files:', ctx.request.files);
}
ctx.body = `Received: ${JSON.stringify(ctx.request.body)}`;
} else {
ctx.body = 'Send a POST, PUT, or PATCH request with a body.';
}
});
const port = 3000;
app.listen(port, () => {
console.log(`Koa server listening on http://localhost:${port}`);
console.log('Try: curl -i http://localhost:3000/users -d "name=test" -X POST');
console.log('Or (for files): curl -i -X POST -F "name=filetest" -F "file=@./package.json" http://localhost:3000/upload');
});