typescriptintermediate

Request ID Tracing Middleware

Express middleware that generates or forwards X-Request-Id headers for distributed tracing.

typescript
import { Request, Response, NextFunction } from 'express';
import { randomUUID } from 'crypto';

export function requestIdMiddleware(req: Request, res: Response, next: NextFunction) {
  const requestId = (req.headers['x-request-id'] as string) || randomUUID();
  req.headers['x-request-id'] = requestId;
  res.setHeader('X-Request-Id', requestId);
  next();
}

Use Cases

  • Distributed tracing
  • Log correlation across microservices

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.