typescript 44 lines · 8 steps

Request correlation IDs in NestJS with AsyncLocalStorage

Attach a correlation ID to every request and read it anywhere without threading it through function arguments.

Explained by highlit
1import { AsyncLocalStorage } from 'node:async_hooks';
2import { randomUUID } from 'node:crypto';
3import { Injectable, NestMiddleware } from '@nestjs/common';
4import { Request, Response, NextFunction } from 'express';
5 
6interface RequestContext {
7 correlationId: string;
8}
9 
10export const requestContext = new AsyncLocalStorage<RequestContext>();
11 
12export function getCorrelationId(): string | undefined {
13 return requestContext.getStore()?.correlationId;
14}
15 
16@Injectable()
17export class CorrelationIdMiddleware implements NestMiddleware {
18 private static readonly HEADER = 'x-correlation-id';
19 
20 use(req: Request, res: Response, next: NextFunction): void {
21 const incoming = req.header(CorrelationIdMiddleware.HEADER);
22 const correlationId = incoming?.trim() || randomUUID();
23 
24 res.setHeader(CorrelationIdMiddleware.HEADER, correlationId);
25 
26 requestContext.run({ correlationId }, () => next());
27 }
28}
29 
30@Injectable()
31export class CorrelatedLogger {
32 private readonly base = new Logger(CorrelatedLogger.name);
33 
34 log(message: string, meta: Record<string, unknown> = {}): void {
35 this.base.log(JSON.stringify({ ...meta, message, correlationId: getCorrelationId() }));
36 }
37 
38 error(message: string, trace?: string): void {
39 this.base.error(
40 JSON.stringify({ message, correlationId: getCorrelationId() }),
41 trace,
42 );
43 }
44}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1AsyncLocalStorage lets you carry per-request state across async boundaries without passing it explicitly.
  2. 2Middleware is the natural place to establish request-scoped context before handlers run.
  3. 3Reusing an incoming correlation header lets traces flow across service boundaries.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Request correlation IDs in NestJS with AsyncLocalStorage — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code