import { randomUUID } from 'crypto'; import { Request, Response, NextFunction } from 'express'; const CORRELATION_HEADER = 'x-request-id'; /** * Middleware that assigns a unique correlation ID to each request. * Uses the incoming x-request-id header if present, otherwise generates a new UUID. * Sets the correlation ID on both the request object and response header. */ export function correlationId(req: Request, res: Response, next: NextFunction) { const id = (req.headers[CORRELATION_HEADER] as string) || randomUUID(); req.correlationId = id; res.setHeader(CORRELATION_HEADER, id); next(); }