Koa Body Parser Middleware

7.0.1 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a Koa application with `koa-body` to parse JSON, urlencoded, and multipart request bodies. It logs the parsed body and any uploaded files, then responds with a confirmation message.

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');
});

view raw JSON →