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;}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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.