Koa Body Parser

4.4.1 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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

view raw JSON →