Request Body Parsing and Error Handling

Parse request bodies with koa-bodyparser, centralize error handling, use ctx.throw, and customize 404 responses.

🎯 Introduction

By the end of this article, your Koa API will accept JSON sent by the frontend through POST requests. You will also have centralized error handling that returns a consistent response format for both success and failure. This is a key step toward turning a demo into a usable API.


🧱 Parse Request Bodies with koa-bodyparser

When the frontend submits data with POST, that data is sent in the request body. Koa's core does not parse request bodies, so install koa-bodyparser. This article was written and verified with Node.js v22 LTS + koa-bodyparser 4.4.1.

npm install koa-bodyparser

After registration, the parsed data is available on ctx.request.body:

app.js
import Koa from 'koa';
import Router from '@koa/router';
import bodyParser from 'koa-bodyparser';

const app = new Koa();
const router = new Router();

// Register before routes so route handlers can access the body
app.use(bodyParser());

router.post('/users', async (ctx) => {
    const data = ctx.request.body; // JSON data sent by the frontend
    ctx.body = { message: 'User created successfully', data };
});

app.use(router.routes());
app.use(router.allowedMethods());

app.listen(3000);

Try sending a POST request from the frontend with fetch:

fetch('http://localhost:3000/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'Alex', age: 18 }),
});

The server can now read the object { name: 'Alex', age: 18 } from ctx.request.body. In addition to JSON, koa-bodyparser parses form data (x-www-form-urlencoded) by default, without extra configuration.

A common mistake: bodyParser() must be registered before routes. Middleware executes in registration order. If a route runs first, ctx.request.body will be undefined.

🧅 Centralized Error Handling with the Onion Model

API code can throw errors for invalid parameters, failed queries, or bugs. Adding try/catch to every route is repetitive and easy to overlook.

Recall that the outermost middleware wraps all downstream processing. A try/catch here can catch errors thrown by downstream middleware:

app.js
// Centralized error handling: register near the beginning
app.use(async (ctx, next) => {
    try {
        await next(); // Catch errors thrown by downstream middleware here
    } catch (err) {
        ctx.status = err.status || 500;
        ctx.body = {
            code: ctx.status,
            message: err.message || 'Internal server error',
        };
        console.error('API error:', err);
    }
});

This is a useful advantage of Koa's error handling. Express uses dedicated error handling middleware with four parameters, while Koa handles errors naturally with await next() and try/catch, including asynchronous errors.


🛠 Throw Errors with ctx.throw

Application logic often needs to reject a request, for example when a required parameter is missing. ctx.throw(statusCode, message) throws an error with a status code for the centralized middleware to handle:

app.js
router.post('/users', async (ctx) => {
    const { name, age } = ctx.request.body;

    // Validate parameters and throw a 400 error if validation fails
    if (!name) {
        ctx.throw(400, 'name is required');
    }

    ctx.body = { message: 'User created successfully', data: { name, age } };
});

When the submitted data is missing name, the API returns:

{
    "code": 400,
    "message": "name is required"
}

Errors thrown by ctx.throw include a status property. The centralized middleware reads it through err.status || 500 to set the appropriate status code.


💡 Handle 404 Responses

By default, Koa returns a 404 status and the plain text Not Found for unmatched requests. When the frontend and backend are separate, we want 404 responses to use the same JSON format too. Add fallback middleware after all routes:

app.js
// Reached only when no route handles the request
app.use(async (ctx) => {
    ctx.status = 404;
    ctx.body = {
        code: 404,
        message: 'Endpoint not found',
    };
});

This follows the onion model's entry order: the request passes through earlier middleware and, if no route handles it, reaches the fallback. Registration order matters. Placing it before the routes would make every request return 404.


🧰 Complete Example: Put It All Together

Combining these pieces gives us a consistent API foundation:

app.js
import Koa from 'koa';
import Router from '@koa/router';
import bodyParser from 'koa-bodyparser';

const app = new Koa();
const router = new Router();

// 1. Centralized error handling (outermost layer)
app.use(async (ctx, next) => {
    try {
        await next();
    } catch (err) {
        ctx.status = err.status || 500;
        ctx.body = { code: ctx.status, message: err.message || 'Internal server error' };
    }
});

// 2. Request body parsing (before routes)
app.use(bodyParser());

// 3. Application routes
router.post('/users', async (ctx) => {
    const { name } = ctx.request.body;
    if (!name) {
        ctx.throw(400, 'name is required');
    }
    ctx.body = { code: 200, message: 'User created successfully', data: { name } };
});

app.use(router.routes());
app.use(router.allowedMethods());

// 4. 404 fallback (last)
app.use(async (ctx) => {
    ctx.status = 404;
    ctx.body = { code: 404, message: 'Endpoint not found' };
});

app.listen(3000);

Remember the registration order: error handling → body parsing → routes → 404 fallback. Each layer's position follows from the onion model.


❓ Questions and Answers

Q1: What is the difference between ctx.request.body and ctx.body?

They represent opposite directions: ctx.request.body contains incoming request data from the client, while ctx.body contains the response sent back to the client.

Q2: Does execution continue after ctx.throw?

No. ctx.throw throws an Error, immediately interrupting the function. The remaining code does not run, and the outer catch block handles the error.

Q3: Can centralized middleware catch errors thrown in async functions?

Yes. This is one benefit of Koa's async/await model. await next() propagates errors from awaited downstream asynchronous operations, allowing one try/catch to handle them.

Q4: What is the code field in the shared error format for?

It lets the frontend check responses consistently. In this example, the frontend checks whether code is 200 and otherwise displays message, rather than handling every status code separately.


🧪 Practice

  1. Write a POST /login endpoint that accepts username and password. If either is missing, call ctx.throw(400, ...) with a message. If both are provided, return JSON indicating a successful login.
app.js
router.post('/login', async (ctx) => {
    // Write your code here
});
  1. Use an API testing tool to test both complete parameters and a missing password. Confirm that errors also use the shared response format.

🎉 You can now build more robust Koa APIs! Next, we will bring everything together by building a complete RESTful user API with in-memory data.