AsyncLocalStorage Correlation Context
Use AsyncLocalStorage for request-scoped correlation IDs without explicit parameter passing.
Code
import{AsyncLocalStorage}from'node:async_hooks';export interface RequestContext{correlationId:string;userId?:string;startTime:number;}const storage=new AsyncLocalStorage<RequestContext>();export function runWithContext<T>(ctx:RequestContext,fn:()=>T):T{return storage.run(ctx,fn);}export function getContext():RequestContext|undefined{return storage.getStore();}export function withCorrelationId<T>(id:string,fn:()=>T):T{return runWithContext({correlationId:id,startTime:Date.now()},fn);}export function getCorrelationId():string|undefined{return getContext()?.correlationId;}Report a problem with this exampleOpens a pre-filled issue on GitHub.