In a Node.js service, `asyncLocalStorage.getStore()` returns undefined, or another request's id, inside callbacks from a pooled client library. Why does that happen, and how do you fix it?
answer
- context follows who scheduled it
- a queue inside the pool
- listeners run in the emitter's context
- bind at hand-over time
- promisify first
basics
~20 sThe callback runs in the async context of whatever triggered it inside the library, such as a freed connection or another request's emit, not where you passed it. Promisify the API, or bind the callback with AsyncLocalStorage.bind or AsyncResource.
solid answer
~50 s`AsyncLocalStorage` propagates the store along the async operations Node can see being created. A pool that keeps your callback in its own queue and calls it later from another operation's completion, a connection being released or a worker's `'message'` event, runs it in that operation's context: you get `undefined`, or the store of the request that triggered it, which is worse. `EventEmitter` listeners likewise run in the context that called `emit()`, and custom thenables can drop context too. Fixes, in order: wrap the callback API with `util.promisify()` so it resolves native promises; bind the callback at hand-over time with `AsyncLocalStorage.bind(fn)` or `AsyncResource.bind(fn)`; in library code, give each queued task an `AsyncResource` and call `runInAsyncScope`. To find the culprit, log `getStore()` after each suspect call; the first `undefined` usually points at the last callback that ran.
code
javascript · 17 linesimport { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage();
const queue = [];
// A tiny pool: callbacks are run by whoever releases the next slot.
function acquire(cb) { queue.push(cb); }
function release() { queue.shift()?.(); }
als.run('req-A', () => {
acquire(() => console.log('plain:', als.getStore()));
acquire(AsyncLocalStorage.bind(() => console.log('bound:', als.getStore())));
});
als.run('req-B', () => { release(); release(); });
// plain: req-B
// bound: req-Ago deeper
Recall that some callback-based libraries lose the AsyncLocalStorage store, and that wrapping them with util.promisify is the first fix to try.
Explain that context follows the async operation that runs a callback, and why a pool's queue or a shared emitter hands you a different context.
Diagnose with getStore() logging, recognise the cross-request leak as a security issue, and choose between promisify, AsyncLocalStorage.bind, snapshot and an AsyncResource per task.
Decide what the team guarantees: which client libraries are approved as context-safe, a concurrency test that interleaves two requests, and which identity fields may ever be trusted from ambient context.
## How the store actually travels `AsyncLocalStorage` does not follow your code's lexical structure; it follows **asynchronous resources**. When code running inside `als.run(store, ...)` creates a promise, a timer, an I/O request or a socket callback, Node records the current context on that operation, and when its callback later runs, that context is restored. That is why `getStore()` still works five awaits deep. The model breaks whenever **the operation that eventually calls your function is not the one your code created**. Your callback is then run in the context of whichever operation actually fired. ## The three common ways context is lost 1. **Pools and internal queues.** A client library with a connection pool often pushes your callback into an array and calls it when *some* connection becomes free. The code that frees the connection is running in the context of the request that finished with it, so your callback inherits **that request's store**. The Node documentation shows exactly this with a `worker_threads.Worker` pool: without explicit tracking, the callbacks look as if they belong to the individual `Worker` objects, because the workers were not created by the tasks. 2. **Event emitters.** An `EventEmitter` calls its listeners synchronously inside `emit()`, so a listener sees the context of the code that emitted, not of the code that called `on()`. A long-lived emitter shared across requests, such as a client's `'data'` or `'error'` event, therefore mixes contexts. 3. **Custom thenables and callback-only code.** Promise-like objects that are not native promises, and some callback-based native bindings, may not be tracked, so the store comes back `undefined`. Getting **another request's id** is more dangerous than getting `undefined`: logs look healthy, and a tenant or user id read from the store could leak into the wrong request. ## The fixes, from cheapest to most invasive - **Promisify.** The documentation's first suggestion: if the API is callback-based, wrap it with `util.promisify()` so your code awaits a native promise. The promise is created inside your context and resolves back into it. - **Bind at hand-over time.** `AsyncLocalStorage.bind(fn)` (stable since 23.11.0 and 22.15.0) or `AsyncResource.bind(fn)` returns a wrapper that runs `fn` in the context that was current when you bound it. Bind the callback at the point you pass it to the library. - **Snapshot a context for later.** `AsyncLocalStorage.snapshot()` captures the current context and returns a runner, `runner(fn, ...args)`, that executes any function inside it. It suits a class that should always run work in the context it was created in. - **Fix it in the library.** If you own the pool, model each queued task as an `AsyncResource` subclass and invoke the user's callback with `this.runInAsyncScope(callback, null, err, result)`, then `emitDestroy()`. For emitters, extend `events.EventEmitterAsyncResource`, whose events all run in the emitter's own async context. | Situation | Context the callback sees | Fix | |---|---|---| | Your own `await` chain | the request's store | none needed | | Pool queue drained by another request | the other request's store | `AsyncLocalStorage.bind`, `AsyncResource` per task | | Shared `EventEmitter` listener | the emitter's caller | `AsyncResource.bind` on the listener | | Callback-only API | often `undefined` | `util.promisify()` | ## Finding the operation that lost it The documentation's method is simple: log `asyncLocalStorage.getStore()` immediately after each call you suspect. When a log shows `undefined` (or the wrong id), the last callback that ran before it is probably responsible. Narrow it to one library call and apply one of the fixes at that boundary. Two more tools help. In Node 24, `--no-async-context-frame` switches back to the older `async_hooks`-based implementation; if a flow behaves differently between the two, Node asks for a bug report. And a context change made with `enterWith()` inside a listener is a frequent self-inflicted cause: it persists for the rest of that synchronous execution, so later listeners on the same event see it as well. ## What not to do - Do not re-read the request id from a "last seen" global as a fallback; that reintroduces the cross-request bug. - Do not call `enterWith()` in a shared listener to "repair" the context. - Do not assume a library is context-safe because one happy-path test passed; test with two concurrent requests whose operations interleave.
- When is `AsyncLocalStorage.snapshot()` a better fit than `bind()`?`bind(fn)` captures the context for one specific function. `snapshot()` captures the current context and returns a runner that executes any function inside it later, so a class can grab it in its constructor and run every method body through it. The docs show it replacing a hand-written `AsyncResource` for that simple case.
- Why is getting another request's id worse than getting `undefined`?`undefined` is visible: log lines show a missing id and the bug gets noticed. A wrong id looks valid, so logs silently attribute work to the wrong request, and if the store carries a user or tenant id, authorisation or data-scoping decisions can use another caller's identity.
- What does `events.EventEmitterAsyncResource` change for listeners?It is an `EventEmitter` that is also an `AsyncResource`. Every event emitted by an instance runs its listeners within the emitter's own async context, captured when the emitter was created, rather than in the context of whatever code happened to call `emit()`.
- Saying AsyncLocalStorage follows the code's lexical scope
- Assuming a lost store always shows up as undefined
- Fixing context loss by calling enterWith() inside a shared listener
- Believing EventEmitter listeners run in the context that registered them
- Blaming the loss on await itself rather than on the library boundary