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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1AsyncLocalStorage lets you carry per-request state across async boundaries without passing it explicitly.
- 2Middleware is the natural place to establish request-scoped context before handlers run.
- 3Reusing an incoming correlation header lets traces flow across service boundaries.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { Cache } from 'cache-manager'; import { InjectRepository } from '@nestjs/typeorm';
A cache-aside country lookup in NestJS
cache-aside
dependency-injection
batch-lookup
Intermediate
8 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core'; interface Preferences { theme: 'light' | 'dark';
A signal-based preferences store in Angular
signals
state-management
persistence
Intermediate
7 steps
typescript
import { useEffect, useState } from "react"; interface Section { id: string;
Building a scroll-spy hook in React
custom-hooks
intersectionobserver
dom-observation
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/request-correlation-ids-in-nestjs-with-asynclocalstorage-explained-typescript-fbc5/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.