AsyncLocalStorage
Prerequisite: node-structured-logs-and-metrics. Objective: Propagate synthetic request id. Local baseline: Node.js 22.16.0 on Linux, ESM. Each example is independent: save as main.mjs in a disposable directory and run node main.mjs. The author harness uses a five-second timeout. Static snippets are not ByteMind interactive execution.
How it works
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.
Preserve context through interleaved promise callbacks
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);Expected output:
A,BtrueEach callback inherits its own store; the outer context is unchanged.
Read a request id across a timer boundary
import {AsyncLocalStorage} from 'node:async_hooks';import {setTimeout as delay} from 'node:timers/promises';const storage=new AsyncLocalStorage();await storage.run({id:'job-5'},async()=>{await delay(1);console.log(storage.getStore().id);});console.log(storage.getStore()===undefined);Expected output:
job-5trueThe timer continuation observes the original request context. No exact timing claim is made.
Common mistakes
Do not assume context propagates into a new worker or that a request id proves identity. Avoid keeping large or secret values in stores.
Practice
Run two concurrent operations with distinct ids and check the store after both finish and outside the run calls.
Reference candidate: node-asynclocalstorage-lookup (route unverified). Documentation: https://nodejs.org/download/release/v22.16.0/docs/api/async_context.html. Exact-version documentation not retrieved in this batch; local fixture behavior tested.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
AsyncLocalStorage — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
Which method establishes a bounded context?
Does AsyncLocalStorage establish authorization?
How should worker correlation be propagated?