Express Correlation ID Middleware

3.0.1 · active · verified Wed Apr 22

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

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to integrate the `express-correlation-id` middleware into an Express application, access the generated or provided correlation ID, and programmatically set a new ID for a request.

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}`);
});

view raw JSON →