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.
npm install koa-jsonVerified import paths — ran on the pinned version, not inferred.
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.
Ensure thorough testing with your specific Koa and Node.js versions. Consider alternative, more actively maintained JSON middleware if advanced features or stricter compatibility guarantees are required, although this package serves its basic purpose reliably.
For parsing incoming JSON request bodies, install and use `@koa/bodyparser` (or `koa-bodyparser`) middleware alongside `koa-json`. Example: `app.use(bodyParser()); app.use(json());`
In production, either set `pretty: false` and omit the `param` option entirely, or ensure that the `param` value is sufficiently obscure or protected by authentication if pretty-printing is required for specific debugging scenarios.
Ensure `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.
Before `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.