Express Correlation ID Middleware
express-correlation-id is an Express middleware that provides a unique correlation identifier for each incoming HTTP request, ensuring consistency across all asynchronous operations within the request's lifecycle. It automatically generates a UUID if no `x-correlation-id` header is present (or a configurable custom header). The library is currently stable at version 3.0.1, with recent updates indicating active maintenance. Version 3.x introduced a breaking change by requiring Node.js 16 or newer, with Node.js 20 being recommended. Its key differentiators include a simple API to access the ID via both the `req` object (`req.correlationId()`) and a static module method (`correlator.getId()`), as well as the ability to programmatically set the ID. It differentiates itself by its focus on robust async context handling for the correlation ID.
Common errors
-
TypeError: correlator.getId is not a function
cause Attempting to destructure `getId` from the `express-correlation-id` module (e.g., `import { getId } from 'express-correlation-id'`) when `getId` is a method on the default exported middleware function object.fixImport the default export and access `getId` as a method: `import correlator from 'express-correlation-id'; const id = correlator.getId();` -
Error: setId can only be called in the context of a request
cause The `correlator.setId()` method was invoked in a global context or outside an active HTTP request's asynchronous scope.fixEnsure `correlator.setId(id)` is only called from within an Express middleware or route handler. If available, use `req.setCorrelationId(id)` as it implicitly operates within the request context. -
ERR_REQUIRE_ESM: require() of ES Module ... not supported
cause Attempting to use `require('express-correlation-id')` in an ES Module-only Node.js project or when a project explicitly configures itself for ESM.fixUse ES Module syntax: `import correlator from 'express-correlation-id';`. Ensure your project's `package.json` has `"type": "module"` or uses `.mjs` file extensions for ESM.
Warnings
- breaking Version 3.0.0 of `express-correlation-id` raised the minimum required Node.js version to 16. Previous versions (2.x) supported Node.js >=12.17.0. Running v3.x on older Node.js environments will lead to compatibility issues.
- gotcha The `correlator()` middleware should be placed strategically after any other middleware that needs to run before the correlation ID is established. The `README` specifically notes it should be placed *after* other middleware.
- gotcha Calling `correlator.getId()` or `correlator.setId(id)` outside the context of an active HTTP request will result in `undefined` for `getId()` or an error for `setId()`.
Install
-
npm install express-correlation-id -
yarn add express-correlation-id -
pnpm add express-correlation-id
Imports
- correlator
const correlator = require('express-correlation-id'); // CommonJS in ESM project import { correlator } from 'express-correlation-id'; // If correlator is default exportimport correlator from 'express-correlation-id';
- correlator.getId
import { getId } from 'express-correlation-id'; // getId is a method on the default export, not a named export.import correlator from 'express-correlation-id'; const id = correlator.getId();
- correlator.setId
import { setId } from 'express-correlation-id'; // setId is a method on the default export, not a named export.import correlator from 'express-correlation-id'; correlator.setId('my-custom-id');
Quickstart
import express from 'express';
import correlator from 'express-correlation-id';
const app = express();
// The correlator middleware should generally be placed after other middleware
// that might need to run before a correlation ID is established.
app.use(express.json()); // Example: other middleware
app.use(correlator());
app.get('/', (req, res) => {
// Access the correlation ID via the request object
console.log('ID for this request (from req.correlationId()):', req.correlationId());
// Access the correlation ID via the module's static method
console.log('ID for this request (from correlator.getId()):', correlator.getId());
res.send(`Correlation ID: ${req.correlationId()}`);
});
app.get('/set-id', (req, res) => {
const newId = `custom-${Math.random().toString(36).substring(2, 9)}`;
req.setCorrelationId(newId); // Set via req object
// correlator.setId(newId); // Alternatively, set via static method
console.log('New ID set for this request:', req.correlationId());
res.send(`New Correlation ID set: ${req.correlationId()}`);
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});