Read JSON, Form, and Text Payloads via ctx.request.body
Parsing Request Bodies
Install and configure koa-bodyparser to parse incoming JSON and form data, then access the parsed payload through ctx.request.body in your handlers.
What you'll learn
- Install koa-bodyparser and mount it as application middleware
- Read parsed JSON and form data from ctx.request.body
- Apply size limits and restrict accepted content types with enableTypes
Koa ships with no body-parsing logic. Before a handler can read ctx.request.body,
you must add koa-bodyparser to the middleware stack. It supports three content
types: json, form (URL-encoded), and text.
Installation
npm install koa-bodyparser Mounting the Middleware
Register bodyparser before your router so that every route handler receives a parsed body.
import Koa from "koa";
import bodyParser from "koa-bodyparser";
import router from "./router.js";
const app = new Koa();
app.use(bodyParser()); // must come first
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000); Reading the Body
After mounting bodyparser, ctx.request.body holds the parsed payload. For JSON
requests it is a plain object; for form-encoded requests it is also an object with
string values.
router.post("/articles", async (ctx) => {
const { title, body } = ctx.request.body;
// persist to database…
ctx.status = 201;
ctx.body = { id: 42, title, body };
}); If the client sends no body or an unsupported Content-Type, ctx.request.body
is an empty object ({}), not null — safe to destructure.
Configuration Options
Pass an options object to fine-tune behaviour:
app.use(
bodyParser({
enableTypes: ["json"], // accept only JSON; reject form/text
jsonLimit: "1mb", // reject bodies larger than 1 MB
strict: true, // only allow arrays and objects at top level
onerror(err, ctx) { // override the default 400 response
ctx.throw(422, "Invalid body: " + err.message);
},
})
); | Option | Default | Purpose |
|---|---|---|
| enableTypes | [‘json’,‘form’,‘text’] | Content types to parse |
| jsonLimit | ’1mb’ | Max JSON body size |
| formLimit | ’56kb’ | Max URL-encoded body size |
| textLimit | ’1mb’ | Max text body size |
| strict | true | Reject non-object JSON roots |
Up Next
With bodies parsed, organise your handler logic into dedicated controller functions to keep routes clean.
Controller Functions →