Koa JSON Response Pretty-Printer

2.0.2 · maintenance · verified Wed Apr 22

koa-json is a Koa middleware designed to pretty-print JSON responses and convert Node.js object streams into binary output. While the package itself, currently at version `2.0.2`, was last updated in April 2016, it remains functional and compatible with recent Koa versions (2.x and 3.x) which utilize async/await middleware. It serves a specific utility by automatically formatting `ctx.body` objects into human-readable, indented JSON, offering options to control pretty-printing behavior via a query string parameter or global configuration. This differentiates it from `koa-bodyparser`, which handles parsing incoming JSON requests. Due to its long-standing stability and the specialized nature of its function, the project's release cadence is effectively dormant, but it continues to be a viable option for adding structured JSON output to Koa applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes a Koa application and applies `koa-json` middleware to automatically pretty-print all JSON responses. It demonstrates setting a simple object on `ctx.body` which `koa-json` then formats, also showing how to enable pretty-printing via a query parameter.

import Koa from 'koa';
import json from 'koa-json';

const app = new Koa();

// Apply the koa-json middleware. By default, it pretty-prints responses.
// You can disable pretty printing by default and enable via a query parameter.
app.use(json({ pretty: true, param: 'pretty' }));

// Define a route that sets a JSON object on ctx.body
app.use(async (ctx) => {
  ctx.body = {
    message: 'Hello, Koa!',
    data: {
      timestamp: new Date().toISOString(),
      version: '1.0.0'
    }
  };
});

const PORT = process.env.PORT ?? 3000;
app.listen(PORT, () => {
  console.log(`Koa server running on http://localhost:${PORT}`);
  console.log('Try accessing / to see pretty JSON.');
  console.log('Or /?pretty to enable pretty printing if default is false.');
});

view raw JSON →