http-ndjson
raw JSON → 3.1.0 verified Sat May 09 auth: no javascript
Log HTTP requests and responses as ndjson (newline-delimited JSON). Version 3.1.0 is the latest stable release. It is designed to work well with bole and garnish for pretty-printing. Minimal dependencies and a focus on standard request/response properties. Use it to produce structured logs that can be piped to other ndjson-consuming tools.
Common errors
error TypeError: httpNdjson is not a function ↓
cause Using destructured import like `const { httpNdjson } = require('http-ndjson')`, which yields undefined.
fix
Use
const httpNdjson = require('http-ndjson') without destructuring. error ERR_REQUIRE_ESM: require() of ES Module not supported ↓
cause Attempting to require() the package in an ESM-only project, but the package is CJS. This error occurs when the project's package.json has "type": "module".
fix
Use dynamic import():
import('http-ndjson').then(m => m.default), or change the project to CommonJS. error TypeError: setSize is not a function ↓
cause Calling httpNdjson without providing a callback, or passing a non-function as the last argument.
fix
Ensure you pass a callback function as the third argument:
const setSize = httpNdjson(req, res, console.log) Warnings
breaking Version 3.0.0 changed the API: the callback signature now receives the message object; previously it received separate arguments. ↓
fix Update your callback to accept the ndjson object directly (e.g., `console.log(msg)` instead of `console.log(msg1, msg2)`).
gotcha The function returns a `setSize` function that must be called with the response body length. Calling it with the wrong value may cause incorrect logging of response size. ↓
fix Always pass the correct byte length of the response body to the returned function (e.g., `setSize(Buffer.byteLength(body))`).
gotcha The package does not support ES modules (ESM). Attempting to import it with `import` will throw an error in Node.js if the project is configured as ESM. ↓
fix Use `require()` or configure your project to use CommonJS. Alternatively, use a dynamic import with a bundler that can handle CJS.
deprecated The `opts` parameter can be a function for custom fields, but this is not deprecated yet. No specific deprecations noted. ↓
fix No action needed.
Install
npm install http-ndjson yarn add http-ndjson pnpm add http-ndjson Imports
- default wrong
import httpNdjson from 'http-ndjson'correctconst httpNdjson = require('http-ndjson') - default wrong
const log = require('http-ndjson').httpNdjsoncorrectconst httpNdjson = require('http-ndjson') - default wrong
const { httpNdjson } = require('http-ndjson')correctconst httpNdjson = require('http-ndjson')
Quickstart
const httpNdjson = require('http-ndjson')
const http = require('http')
http.createServer((req, res) => {
const log = console.log
const setSize = httpNdjson(req, res, log)
const body = 'OK'
setSize(body.length)
res.end(body)
}).listen(3000, () => console.log('Server listening on 3000'))