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 { Controller, Get, Query,
Validating paginated queries in NestJS
pagination
validation
pipes
Intermediate
7 steps
rust
use axum::{ body::{Body, Bytes}, extract::Request, http::StatusCode,
Logging request bodies in Axum middleware
middleware
streaming-body
logging
Intermediate
8 steps
rust
use std::time::Duration; use axum::{ body::Body,
Turning Axum timeouts into 504 JSON
middleware
timeouts
error-handling
Intermediate
7 steps
go
package middleware import ( "net/http"
A per-IP rate limiter middleware in Gin
rate-limiting
token-bucket
middleware
Intermediate
8 steps
typescript
import { Controller, Post, UploadedFile,
Handling avatar uploads in NestJS
file-upload
validation
interceptors
Intermediate
7 steps
typescript
@Component({ selector: 'app-article-editor', templateUrl: './article-editor.component.html', })
Autosaving a form with RxJS in Angular
reactive-forms
rxjs-operators
debouncing
Advanced
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.