AsyncLocalStorage Correlation Context

Use AsyncLocalStorage for request-scoped correlation IDs without explicit parameter passing.

TypescriptCli Tooling

Code

typescriptsnippet
1 line
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;}

How the snippet works

Count the functions runWithContext, getContext, withCorrelationId and getCorrelationId as the entire surface area of AsyncLocalStorage Correlation Context.

The only import source is node:async_hooks, a Node.js built-in, exposing AsyncLocalStorage.

Watch out for

  • The only import, node:async_hooks, is part of the Node.js standard library.

Using it

runWithContext is what another module would consume; nothing else here is load-bearing for callers.

Interactive Tools for This Topic

FAQ

Is the imported module an npm package?
No — `node:async_hooks` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.