Koa JSON Response Pretty-Printer
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
-
Error: `obj` must be an object (koa-json internal error or similar)
cause `koa-json` received `ctx.body` that was not an object, array, or stream that could be serialized into JSON.fixEnsure `ctx.body` is set to a valid JavaScript object, array, or a Node.js object stream before `koa-json` middleware processes the response. `koa-json` expects a serializable structure. -
TypeError: Converting circular structure to JSON
cause Attempting to serialize a JavaScript object with circular references within `ctx.body`.fixBefore `koa-json` processes the response, ensure that any objects assigned to `ctx.body` do not contain circular references. Manually serialize complex objects or use a library to handle circular references if necessary, or filter out problematic properties.
Warnings
- gotcha The `koa-json` package has not been updated since April 2016. While it remains compatible with modern Koa versions (2.x and 3.x), it means no new features or direct compatibility fixes for very recent Node.js changes will be provided. The core functionality, however, is stable.
- gotcha Confusion with `koa-bodyparser`: `koa-json` is solely for pretty-printing *outgoing* JSON responses. It does not parse *incoming* JSON request bodies. Using `ctx.request.body` will be `undefined` if you expect it to parse incoming JSON without `koa-bodyparser` or similar middleware.
- gotcha The `param` option in `koa-json` can unintentionally expose pretty-printed JSON in production environments if not carefully managed. If `pretty: false` is the default, but `param: 'pretty'` is set, appending `?pretty` to any URL will force pretty-printed output, which might expose internal data structures or increase response size.
Install
-
npm install koa-json -
yarn add koa-json -
pnpm add koa-json
Imports
- json
import { json } from 'koa-json';import json from 'koa-json';
- json (CommonJS)
import json from 'koa-json';
const json = require('koa-json'); - Middleware setup
app.use(json);
app.use(json({ pretty: true, spaces: 2 }));
Quickstart
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.');
});