Node.js › Express & Middleware

How would you implement a middleware that adds a correlation/request ID to every incoming request for tracing purposes across a distributed system?

Advanced

Answer

A correlation-ID middleware checks for an existing ID from an incoming header (allowing the ID to be propagated from an upstream service in a microservices architecture), generating a new one if absent, attaching it to the request object (or an AsyncLocalStorage context) so every subsequent log statement and downstream call within that request can include it, and setting it on the response header so the caller can correlate their own logs with the server's.
app.use((req, res, next) => {
  req.correlationId = req.headers['x-correlation-id'] || crypto.randomUUID();
  res.set('x-correlation-id', req.correlationId);
  next();
});

// Later, in any log statement within this request's lifecycle
logger.info(`[${req.correlationId}] Processing order`);
Real-world example A microservices architecture propagates a single correlation ID from the initial API gateway request all the way through every downstream service call, letting an engineer search their centralized logging system for one ID and see the complete, ordered trail of what happened across every service involved in handling that one request.

Common follow-ups: How does this hand-rolled correlation ID approach compare to using a full distributed tracing system like OpenTelemetry?;How would you ensure this correlation ID survives across an asynchronous boundary like a background job triggered by the request?