{"id":17082,"library":"bunyan-middleware","title":"Bunyan HTTP Middleware Logger","description":"bunyan-middleware is a Node.js middleware for logging HTTP requests and responses using the Bunyan logger. Currently at version 1.0.2, it appears to be a stable project, though its release cadence is not explicitly stated. This library offers robust features for integrating structured logging into Express, Connect, or pure HTTP servers. Key differentiators include automatic management of the `X-Request-Id` header (generating a UUID if not present), logging request-response duration, providing a request-scoped logger (`req.log`) for tracing individual requests throughout an application, and custom serializers for `req` and `res` objects. It also provides functionality to obscure sensitive headers in log outputs, enhancing security and compliance. It is a direct dependency of an existing Bunyan logger instance, allowing for consistent logging configuration.","status":"active","version":"1.0.2","language":"javascript","source_language":"en","source_url":"git://github.com/tellnes/bunyan-middleware","tags":["javascript","bunyan","logger","express","request","response","connect","http","duration","typescript"],"install":[{"cmd":"npm install bunyan-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add bunyan-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add bunyan-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"This middleware requires an instantiated Bunyan logger to function, passed via the `logger` option.","package":"bunyan","optional":false}],"imports":[{"note":"This package is distributed as a CommonJS module. For TypeScript, use `import bunyanMiddleware = require('bunyan-middleware')`. For ESM projects, direct `import` syntax might require bundler configuration or a CommonJS wrapper.","wrong":"import bunyanMiddleware from 'bunyan-middleware'","symbol":"bunyanMiddleware","correct":"const bunyanMiddleware = require('bunyan-middleware')"},{"note":"TypeScript types are nested under the main `bunyanMiddleware` export.","symbol":"BunyanMiddlewareOptions","correct":"import bunyanMiddleware = require('bunyan-middleware');\ntype Options = bunyanMiddleware.BunyanMiddlewareOptions;"}],"quickstart":{"code":"const bunyan = require('bunyan')\nconst bunyanMiddleware = require('bunyan-middleware')\nconst express = require('express')\n\nconst app = express()\nconst logger = bunyan.createLogger({ name: 'My App', level: process.env.LOG_LEVEL || 'info' })\n\napp.use(bunyanMiddleware(\n    { headerName: 'X-Request-Id'\n    , propertyName: 'reqId'\n    , logName: 'req_id'\n    , obscureHeaders: ['authorization', 'cookie'] // Example: obscure sensitive headers\n    , logger: logger\n    , additionalRequestFinishData: function(req, res) {\n        // Add custom data to the 'request finish' log message\n        return { exampleCustomData: 'value' }\n      }\n    }\n  )\n)\n\napp.get('/', function (req, res) {\n  // Use `req.log` for request-specific logging, automatically including the request ID.\n  req.log.info({ user: 'guest' }, 'Accessed home route')\n  res.send('Hello, Bunyan Logger!')\n})\n\nconst port = process.env.PORT || 3000;\napp.listen(port, () => {\n  logger.info(`Server listening on port ${port}`);\n});","lang":"typescript","description":"This example demonstrates setting up bunyan-middleware with Express, configuring request ID handling, obscuring headers, adding custom finish data, and utilizing the request-scoped `req.log`."},"warnings":[{"fix":"For TypeScript, use `import bunyanMiddleware = require('bunyan-middleware')`. For ESM-only JavaScript, consider using a CommonJS wrapper or a bundler that correctly handles CommonJS modules.","message":"This package is distributed as a CommonJS module. In modern TypeScript or pure ESM projects, a direct `import bunyanMiddleware from 'bunyan-middleware'` will likely fail or require specific bundler configurations. The recommended TypeScript import is `import bunyanMiddleware = require('bunyan-middleware')`.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Always pass an initialized Bunyan logger instance to the `bunyanMiddleware` options, e.g., `logger: bunyan.createLogger({ name: 'my-app' })`.","message":"The `logger` option is a required configuration. Failing to provide a valid Bunyan logger instance will result in runtime errors as the middleware attempts to use it.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure that if you provide custom `req` serializers, they correctly reference `req.originalUrl` or the desired URL property for accurate logging in mounted Express applications.","message":"When using `bunyan-middleware` with Express mounted apps that rewrite `req.url`, the default Bunyan `req` serializer might log the rewritten URL instead of the original. `bunyan-middleware` provides its own serializer using `req.originalUrl` to mitigate this, but custom serializer overrides could reintroduce this behavior.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"In TypeScript or CommonJS, use `const bunyanMiddleware = require('bunyan-middleware')`. If forced to use ESM `import` in a modern Node.js environment, ensure your `tsconfig.json` or bundler settings handle CommonJS imports correctly, or wrap `require` in a utility function.","cause":"Attempting to use `import bunyanMiddleware from 'bunyan-middleware'` in an ESM context without proper CommonJS interoperability configuration, leading to the module object being imported instead of the default export function.","error":"TypeError: bunyanMiddleware is not a function"},{"fix":"Verify that the header names in the `obscureHeaders` array exactly match the casing of the incoming HTTP headers. Double-check that `bunyan-middleware` is applied early in your middleware stack to obscure headers before other logging mechanisms capture them.","cause":"The `obscureHeaders` option is case-sensitive or not configured correctly, or the headers are being logged by other means before `bunyan-middleware` processes them.","error":"Sensitive headers (e.g., Authorization, Cookie) are appearing in logs despite `obscureHeaders` being configured."}],"ecosystem":"npm","meta_description":null}