What is AsyncLocalStorage in Node.js and what problem does it solve?
AsyncLocalStorage is a class exported from node:async_hooks. It lets you attach a value, called a store, to a unit of asynchronous work. You start the work with run(store, callback). Any code that executes as part of that callback can read the same store with getStore(), including code reached through promises, timers, and I/O callbacks. You do not have to pass the store anywhere.
This matters because Node.js has no thread-local storage that maps to a request. A single event loop interleaves many requests. While request A waits on a database query, request B's handler runs, and then A's continuation resumes. A module-level variable such as currentUser would be overwritten by whichever request touched it last, so it cannot hold per-request state.
The usual workaround is to thread req, a request ID, or a child logger through every function. That has two problems:
- Signature pollution. A pure function like
computeDiscountgains actxparameter only so it can pass it to a logger three calls down. - Library boundaries. When your code calls into an ORM, an HTTP client, or an event emitter, you cannot add parameters to its callbacks. The context is lost there.
This guide is for backend and platform engineers who own logging, tracing, and tenant scoping, where every log line and query needs to know which request it belongs to. It treats AsyncLocalStorage as a narrow mechanism with a deliberate scope: it carries cross-cutting request context. It is not a general-purpose global state store.
Who should use AsyncLocalStorage?
AsyncLocalStorage fits teams and engineers who have a specific problem: per-request data must be available deep in a call graph they do not fully control.
- Platform and infrastructure engineers who maintain shared logging, metrics, or tracing libraries. They need every log line or span to carry a request ID without asking every application team to change function signatures.
- Backend engineers on large Node.js services with deep call graphs, many modules, and heavy use of third-party clients. Here, threading a context argument through every layer is expensive and breaks at library callbacks.
- Teams building multi-tenant systems that want a tenant ID available to a data-access layer as a safety check. That code should still fail loudly when the ID is missing, as the cost section below explains.
- Framework and middleware authors who want to expose "the current request" to user code without requiring users to pass it around.
It is a poor fit for small services with shallow call graphs, where passing a context object explicitly costs little. It is also a poor fit for code paths where business decisions depend on the value, because a hidden input is harder to review and test than an explicit argument. If you cannot write the integration tests described later in this article, prefer explicit passing.
How does AsyncLocalStorage work?
At its core, AsyncLocalStorage relies on Node's internal tracking of asynchronous resources. Each promise, timer, and I/O request is an async resource. Node already knows which resource caused another one to be created, because it needs that information for features like async stack traces and the async_hooks API.
AsyncLocalStorage uses this tracking to associate a store with the current execution context:
run(store, callback)setsstoreas the active value for this instance, callscallbacksynchronously, and restores the previous value whencallbackreturns or throws.- When a new async resource is created while a store is active, the current context, including that store, is captured and attached to the resource.
- When the resource's continuation runs, Node makes the captured context active again for the duration of that continuation, then restores whatever was active before.
getStore()reads the value for this instance from the currently active context. If norun()is in effect for this instance, it returnsundefined.
The original implementation used async_hooks lifecycle callbacks to copy the store onto each new resource. Newer Node.js releases have moved to an implementation built on V8's support for carrying embedder data across promise continuations, which reduces per-resource bookkeeping. The public API and the propagation behavior described in this article are the same either way. Your code should depend only on run(), getStore(), and the bind helpers, not on which mechanism is underneath.
Because the store travels with async resources rather than with the call stack, the model has one consequence you will see throughout this guide. Context follows whoever created the async work, not whoever registered the callback. The next section walks through that rule in detail.
How does AsyncLocalStorage propagate context across async boundaries?
The API surface is small. Create one AsyncLocalStorage instance per kind of context: one for request context, and a separate one if you also track something unrelated, such as a tenant override for background jobs. Separate instances keep unrelated concerns from overwriting each other's stores. Call run(store, callback) to establish a scope. Inside callback, and inside everything it causes to happen later, getStore() returns that store. Outside any scope it returns undefined, so code that reads context must handle that case rather than assume a value exists.
The propagation rule explains why this works without passing arguments. When code creates an async resource, such as a promise, a timer, or an I/O request, Node records the store that is active at that moment. When the resource's continuation runs later (a .then handler, the code after an await, a timer callback, a socket callback), Node restores that recorded store before executing it and restores the previous one afterward. The store is attached to the async resource, not to a global variable, so it does not matter what else ran in the meantime.
As a result, context follows the causal async chain. It does not follow the call stack, which is empty between ticks, and it does not follow wall-clock time. Two requests can interleave freely on one event loop:
| Event loop tick | Running continuation | Created under | getStore() returns |
|---|---|---|---|
| 1 | Request A handler | run(storeA) |
storeA |
| 2 | Request B handler | run(storeB) |
storeB |
| 3 | A's DB query resolves | A's promise | storeA |
| 4 | B's timer fires | B's timer | storeB |
| 5 | A's response write completes | A's I/O | storeA |
Each continuation sees the store that was active when its resource was created, regardless of which request ran just before it.
const { AsyncLocalStorage } = require('node:async_hooks');
// One instance per kind of context: this one holds request context only.
const requestContext = new AsyncLocalStorage();
function log(msg) {
// getStore() returns undefined outside any run() scope, so handle that case.
const store = requestContext.getStore();
const id = store ? store.requestId : 'no-context';
console.log(`[${id}] ${msg}`);
}
// Stand-in for a DB call: a promise resolved later by a timer.
const fakeDbQuery = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function handleRequest(dbDelayMs, timerDelayMs) {
log('handler start');
// The timer captures the active store when it is created.
setTimeout(() => log('timer fired'), timerDelayMs);
// The code after await runs with the store that was active before the await.
await fakeDbQuery(dbDelayMs);
log('db query resolved');
}
// Two requests interleave on one event loop, each with its own store.
requestContext.run({ requestId: 'req-A' }, () => handleRequest(30, 10));
requestContext.run({ requestId: 'req-B' }, () => handleRequest(5, 20));
log('top level, outside any scope');
// Expected output (order set by the delays, not by which request started first):
// [req-A] handler start
// [req-B] handler start
// [no-context] top level, outside any scope
// [req-B] db query resolved
// [req-A] timer fired
// [req-B] timer fired
// [req-A] db query resolved
Two requests run in separate run() scopes and interleave their timers and awaited promises, yet each continuation logs its own requestId, while code outside any scope sees undefined.
How do you implement request context and logging context with AsyncLocalStorage?
Wrap each request in run() at the outermost layer: the first middleware or the server's request handler itself. Anything registered before that point, such as a body parser that runs earlier, executes outside the context and cannot see it.
Inside the wrapper, read an incoming request ID header if your edge proxy sets one; otherwise generate one with crypto.randomUUID(). Build a small object holding requestId, tenantId, userId, and a child logger. Then call als.run(store, next) so the rest of the chain executes inside that scope.
Some fields only become known partway through the request. For example, userId is known only after authentication succeeds. To record it, mutate the existing object: als.getStore().userId = user.id. Every continuation already holds a reference to that same object, so they all see the update. Calling run() again with a new object behaves differently. It creates a nested scope, and only code inside that inner callback sees the new value. Once the callback returns, and in any continuation created outside it, the old store is back. Use nesting when you want to scope something, not when you want to update it.
The logger wrapper should call getStore() on every log call, not once at startup. It merges the request fields into each line. If no store exists, as with startup code, cron jobs, or lost context, it should log without request fields instead of throwing.
Prefer run() over enterWith(). enterWith() sets the store for the rest of the current synchronous execution and everything it schedules, with no defined end. If it runs in shared code, such as an event listener on a pooled socket, later requests can inherit the earlier request's context.
const { AsyncLocalStorage } = require('node:async_hooks');
const { randomUUID } = require('node:crypto');
const als = new AsyncLocalStorage();
// Thin logger: reads the store on every call and never caches it.
function log(level, msg, extra = {}) {
const store = als.getStore();
// No store (startup, cron jobs, lost context): log without request fields.
const ctx = store
? { requestId: store.requestId, tenantId: store.tenantId, userId: store.userId }
: {};
console.log(JSON.stringify({ level, msg, ...ctx, ...extra }));
}
// Register FIRST so every later middleware and handler runs inside the scope.
function requestContext(req, res, next) {
const store = {
// Reuse the edge proxy's ID if present so logs correlate across hops.
requestId: req.headers['x-request-id'] || randomUUID(),
tenantId: req.headers['x-tenant-id'] || null,
userId: null, // unknown until authentication succeeds
};
als.run(store, next); // scope ends with this request's async chain
}
// Placeholder for real token verification.
async function verifyToken(header) {
return { id: 'user_123' };
}
// Mutate the shared object; calling run() here would only create a nested scope.
async function authenticate(req, res, next) {
const user = await verifyToken(req.headers.authorization);
const store = als.getStore();
if (store) store.userId = user.id; // visible to all later continuations
log('info', 'authenticated');
next();
}
module.exports = { als, log, requestContext, authenticate };
Middleware that wraps each request in als.run() with a request ID, a later auth step that fills in userId by mutating the existing store, and a logger that reads getStore() on every call and still logs when no store is present.
Where does request context get lost, and how do you re-attach it?
The most common failure is silent. A library that pools or queues work stores your callback and invokes it later from a different async origin: a connection pool's socket handler, a custom event emitter fired by unrelated code, or a hand-rolled job queue drained on a timer. Propagation follows the async resource that scheduled the callback, not the function that registered it. Inside the callback, getStore() returns undefined, or worse, the store of whichever request triggered the drain. Nothing throws. You only notice when log lines stop carrying request IDs or carry the wrong ones.
Re-attaching context
The fix is to capture the context when the work is enqueued, not when it runs:
AsyncLocalStorage.bind(fn)returns a wrapper that runsfnin the context active at bind time. This is the lightest option for a single callback passed into a pool or emitter.AsyncResource.bind(fn)does the same and also registers the function as an async resource, so it is visible to async hooks.AsyncResourcewithrunInAsyncScope()suits a queue or pool you own. Create one resource per queued item at enqueue time and callrunInAsyncScope()when you dispatch it.
Process and instance boundaries
Context never crosses worker threads, child processes or network hops, because each has its own async graph. Serialize the fields you need into the message payload or request headers, then call run() with a reconstructed store on the receiving side.
Separate AsyncLocalStorage instances are also independent. If your logger and a tracing library each keep their own store, a request ID copied into both can drift apart after a re-attach that updates only one of them.
const { AsyncLocalStorage, AsyncResource } = require('node:async_hooks');
const als = new AsyncLocalStorage();
const log = (label) => console.log(label, als.getStore()?.requestId);
// Hand-rolled job queue. The drain timer is created at module load,
// outside any request, so jobs run in the timer's async context.
const queue = [];
setTimeout(function drain() {
for (const job of queue.splice(0)) {
if (job.resource) {
// Restore the context captured at enqueue time, then release it.
job.resource.runInAsyncScope(job.fn);
job.resource.emitDestroy();
} else {
job.fn();
}
}
}, 50);
function enqueueNaive(fn) {
queue.push({ fn });
}
function enqueueWithResource(fn) {
// One AsyncResource per item, created while the caller's context is active.
queue.push({ fn, resource: new AsyncResource('app.queue.job') });
}
als.run({ requestId: 'req-7f3a9c' }, () => {
// Lost: prints undefined, and nothing throws.
enqueueNaive(() => log('naive:'));
// Re-attached by the queue owner: prints req-7f3a9c.
enqueueWithResource(() => log('resource:'));
// Re-attached by the caller with a bound wrapper: prints req-7f3a9c.
enqueueNaive(AsyncLocalStorage.bind(() => log('bind:')));
});
A timer-drained job queue loses the request ID silently, and the example re-attaches it either with a per-item AsyncResource and runInAsyncScope() or by wrapping the callback with AsyncLocalStorage.bind() at enqueue time.
How do you test for context bleed and lost context?
Single-request unit tests rarely catch these bugs. With one request in flight, a leaked store and a correct store hold the same value, so the assertion passes either way. Bleed only shows up when two requests interleave on the event loop, which means your test has to create that interleaving on purpose.
A practical test starts the server in-process and fires a few hundred requests at once with Promise.all. Each request carries a unique ID in a header. Add a small random delay inside the handler so that continuations from different requests interleave. Capture log output into an array instead of stdout. Then assert two things: every response echoes the ID it was sent, and every captured log line carries the ID of the request that produced it. Also assert that no line has an empty ID, because that is how lost context shows up, and it is a separate failure from bleed.
The usual causes of bleed are worth testing for directly:
enterWith()replaces the store for the rest of the current synchronous execution and everything it schedules. If it runs outside a scopedrun(), the next request can inherit it.- Module-level caching, such as calling
getStore()once and saving the result in a variable or a memoized helper, freezes one request's context for all later callers. - Long-lived objects created during one request and reused later, such as a lazily built client, a cached promise, or an event emitter with listeners, can carry the first request's context into the next one.
Write an integration test like this around each pooled or queue-based dependency: database drivers, HTTP agents, job queues, and batching loaders. Some of these libraries preserve context through their pools and some do not, and that can change between releases. A test that runs on every dependency upgrade will catch a regression.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';
import { setTimeout as sleep } from 'node:timers/promises';
const als = new AsyncLocalStorage();
const lines = []; // capture logs in memory instead of writing to stdout
const log = (msg) => lines.push({ id: als.getStore()?.id ?? '', msg });
const server = http.createServer((req, res) => {
als.run({ id: req.headers['x-request-id'] }, async () => {
log('start');
await sleep(Math.random() * 20); // random delay forces requests to interleave
log('end');
res.end(als.getStore()?.id ?? '');
});
});
test('no context bleed or loss under concurrent load', async () => {
await new Promise((resolve) => server.listen(0, resolve));
const { port } = server.address();
const ids = Array.from({ length: 300 }, (_, i) => `req-${i}`);
const bodies = await Promise.all(ids.map((id) =>
fetch(` { headers: { 'x-request-id': id } })
.then((r) => r.text())));
server.closeAllConnections();
server.close();
// Each response must echo the ID it was sent
ids.forEach((id, i) => assert.equal(bodies[i], id));
// An empty ID means context was lost, which is a separate failure from bleed
assert.ok(lines.every((l) => l.id !== ''), 'lost context');
// Each request wrote exactly two lines; a borrowed ID skews these counts
for (const id of ids) {
assert.equal(lines.filter((l) => l.id === id).length, 2, `bleed for ${id}`);
}
});
A node:test integration test that sends 300 concurrent requests with distinct IDs to an in-process server and checks that every response and every captured log line carries its own request's ID, with no lines missing an ID.
How can AsyncLocalStorage save engineering time?
The time savings come from removing repetitive plumbing work and from shortening debugging, not from making code run faster.
Less signature churn. Without a context store, adding a new field to request context, such as a feature-flag cohort or a trace sampling decision, means editing every function between the handler and the code that needs the field. With AsyncLocalStorage, you add the field in one middleware and read it where needed. Code review is smaller, and merge conflicts in widely shared signatures go away.
Context at library boundaries without forks or wrappers. Callbacks from an ORM, HTTP client, or event emitter can log with the right request ID without wrapping each library in a context-aware shim. Where a library does lose context, a single AsyncLocalStorage.bind() at the call site fixes it, instead of a parameter threaded through several layers.
Faster incident investigation. When every log line carries a request ID and tenant ID automatically, an engineer can filter logs for one failing request instead of reconstructing its path from timestamps across interleaved requests. This is usually the largest saving, because it happens under time pressure.
One owner for cross-cutting concerns. A platform team can ship request-scoped logging and tracing as a library. Application teams get correlated logs by registering one middleware, rather than each team building and maintaining its own context passing.
As an illustrative estimate, with all inputs assumed rather than measured: suppose a service has 40 functions between its handlers and its logging calls, and the team adds a new context field about four times a year. If threading a field through takes an assumed 5 minutes per function, including review, each addition costs about 200 minutes, or roughly 13 hours a year. With a context store, each addition is an assumed 30 minutes of middleware and logger changes, about 2 hours a year. Plug in your own function count, change frequency, and per-change cost. Then subtract the one-time cost of wiring and the integration tests described above before deciding.
These savings depend on the testing discipline in the previous section. Context lost without warning can cost more time than it saves, because the symptom (missing or wrong IDs in logs) often surfaces only during an incident.
When should you avoid AsyncLocalStorage, and what does it cost?
Hidden inputs. A function that calls getStore() depends on state that its signature does not show. Readers can't tell what it needs, and a unit test has to wrap the call in run() or the function silently gets undefined. Keep the store at the edges: logging, tracing, and metrics. Business logic should take tenantId or userId as explicit arguments, and the request handler should read them from the store once and pass them down.
Runtime overhead. Async context tracking adds work to every promise and callback. How much depends on the Node.js version and on how many async operations each request creates. Don't plan around a number from someone else's benchmark. Load-test your own service with and without the store active, and compare latency percentiles and CPU.
Memory retention. Every continuation a request spawns holds a reference to the store, including stray setInterval timers and long-lived event listeners. If the store holds a request body or a database client, those objects stay alive as long as any of those continuations do. Store small identifiers and look up heavy objects when you need them.
Data isolation. If queries are scoped by a tenantId read from the store, lost or wrong context becomes a cross-tenant data leak. When the store is missing, throw an error. Never fall back to a default tenant or an unscoped query.
Development cost. You pay up front for wiring and for tests like the ones above. In return, you stop threading context through every signature, and you get correlated logs during incidents. That trade usually favors AsyncLocalStorage in large services with deep call graphs. It is harder to justify in small services where passing context explicitly is cheap.
What are the alternatives to AsyncLocalStorage for request context?
| Approach | Explicitness | Testability | Across library boundaries | Silent-loss risk | Adoption effort |
|---|---|---|---|---|---|
Thread req or a context object |
Full | Easy: pass a fake | Only where you control signatures | None; compiler or linter flags gaps | High in existing code |
| Per-request logger via DI | High | Easy: inject a test logger | Stops at code you don't wire | Low | Medium; needs a container or factories |
| Data on framework request object | Medium | Needs a request fixture | Ends at the handler layer | Low, but couples domain code to HTTP | Low |
| Tracing library's propagation | Low | Needs SDK test setup | Good where instrumented | Medium; depends on instrumentation | Low to medium |
Argument threading makes the dependency visible in every signature. That visibility is its main benefit and its main cost. A function that needs a tenant ID says so, and a missing argument fails loudly. The trade is churn: adding one field can touch dozens of signatures.
DI-scoped loggers keep that explicitness for logging and contain the churn. Code outside your container, such as a third-party client's retry callback, still never sees the logger.
Hanging data off the request object is cheap to adopt. It breaks down once work leaves the handler for queues, jobs or shared services that have no request object.
Tracing propagation handles spans well. In Node, it is often built on AsyncLocalStorage, so it inherits the same loss points.
Prefer explicit passing for anything that drives business logic. Use AsyncLocalStorage only for cross-cutting concerns such as logging, tracing and tenant scoping. In those cases, a missing value should degrade an observability signal rather than change behavior.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to asynclocalstorage nodejs, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.