AsyncLocalStorage
AsyncLocalStorage keeps context available across related asynchronous operations without passing it through every function. It is often used for request correlation, not for granting permissions. Create one AsyncLocalStorage instance, call run(store, callback) at a request boundary, and retrieve the store with getStore inside descendant asynchronous work. Outside a context getStore normally returns undefined. Concurrent requests should use separate stores; mutating a shared object can still leak values. Prefer run over enterWith for bounded scope. AsyncResource can bridge some callback APIs that lose context. A worker thread has a separate isolate; pass only explicitly approved correlation metadata in messages. Do not assume context propagates into a new worker or that a request id proves identity. Avoid keeping large or secret values in stores. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/async_context.html.
Formal Syntax & Structure
new AsyncLocalStorage(); storage.run(store, callback); storage.getStore()Working Example
import {AsyncLocalStorage} from 'node:async_hooks';import assert from 'node:assert/strict';const context=new AsyncLocalStorage();const run=id=>context.run({id},async()=>{await Promise.resolve();return context.getStore().id;});const ids=await Promise.all([run('A'),run('B')]);assert.deepEqual(ids,['A','B']);console.log(ids.join(','));console.log(context.getStore()===undefined);