Request Context (correlation id, per-request state)
On this page
What Request Context Solves
Production debugging depends on correlating logs and traces to a single request. A request context carries metadata like requestId, userId, and feature flags through your call chain.
Simple Context via req
The simplest approach is attaching context to req and reading it consistently. This is explicit, testable, and works across async boundaries.
import type { Request, Response, NextFunction } from 'express';
import crypto from 'crypto';
export function requestId(req: Request, _res: Response, next: NextFunction) {
(req as any).requestId = crypto.randomUUID();
next();
}
AsyncLocalStorage Option
For deeper call stacks where passing req is noisy, AsyncLocalStorage can provide context propagation. Use it carefully and measure overhead; correctness and observability are the priority.