How-To Guide

How to Use AsyncLocalStorage for Request Context

Propagate request-scoped context such as trace ids and tenant ids through async calls with AsyncLocalStorage, without threading arguments everywhere.

On this page

  1. Introduction
  2. The Problem with Global and Threaded Context
  3. Seeding the Store at the Boundary
  4. Reading the Context Deep in the Stack
  5. Propagation Across Async Boundaries
  6. Performance and Memory
  7. Common Pitfalls and Conclusion

Introduction

A request has context that many layers need: the trace id, the authenticated user, the tenant, a deadline. Passing that context as an argument through every function is noisy and easy to forget, yet storing it in a module-level variable is a data race the moment two requests overlap. Node.js solves this with AsyncLocalStorage, a store that follows the asynchronous call chain, so code deep in a promise chain can read the request context without it being passed explicitly, and concurrent requests never see each other’s context.

The Problem with Global and Threaded Context

A module-level variable holding the current request is wrong under concurrency: request A sets it, request B overwrites it, and A reads B’s value. Threading the context as a parameter is correct but invasive: every signature between the entry point and the leaf needs the extra argument, and a single forgotten call breaks the chain.

AsyncLocalStorage gives you the ergonomics of a global with the isolation of a parameter. Each asynchronous execution context has its own store, and the store is inherited by promises, timers and callbacks launched within it. Two concurrent requests have two stores, and code in either reads the right one.

import { AsyncLocalStorage } from 'node:async_hooks';

interface RequestContext { traceId: string; userId?: string; tenant: string; }

export const requestContext = new AsyncLocalStorage<RequestContext>();

// At the request boundary, run the whole handler inside the store.
export function withRequestContext<T>(ctx: RequestContext, fn: () => T): T {
  return requestContext.run(ctx, fn);
}

Seeding the Store at the Boundary

The store is entered once, at the request boundary, with run(). Everything that handler initiates inherits it, including awaited calls and timers scheduled inside. The rule is to wrap the outermost handler so no code runs outside the store, otherwise a leaf function sees an empty store and falls back to a default that is misleading.

Build the context where the request’s identity is known: the HTTP middleware, the job runner, the message consumer. Populate the trace id from the active span and the user from the authenticated session, and keep the object small and immutable. Mutating it deep in the stack makes the context unpredictable.

import { randomUUID } from 'node:crypto';

export function middleware(req: Request, next: () => Promise<Response>) {
  const ctx = {
    traceId: req.headers.get('traceparent')?.split('-')[1] ?? randomUUID(),
    tenant: req.headers.get('x-tenant') ?? 'public',
    userId: undefined as string | undefined,
  };
  return requestContext.run(ctx, () => next()); // whole request in the store
}

Reading the Context Deep in the Stack

Leaf code reads the store rather than receiving the context. A logger can pull the trace id, a database wrapper can validate the tenant, a metrics helper can tag the route, all without an argument. This is what makes structured logging and tracing tractable: the ids are always available where the log line is written.

Always handle the case where no store is active. A background task started outside any request has no context; getStore() returns undefined, and the code should fall back to a sensible default rather than throwing. A helper that returns a default context is safer than a non-null assertion that crashes a cron job.

export function currentContext(): RequestContext {
  return requestContext.getStore() ?? { traceId: 'none', tenant: 'system' };
}

export function logInfo(message: string, fields: Record<string, unknown> = {}) {
  const ctx = currentContext();
  console.log(JSON.stringify({
    level: 'info',
    message,
    traceId: ctx.traceId,
    tenant: ctx.tenant,
    ...fields,
  }));
}

Propagation Across Async Boundaries

AsyncLocalStorage follows promises, async/await and timers automatically. It does not follow callbacks that are stored and invoked in a different context later, unless the store was captured when the callback was created. Event emitters and pub/sub callbacks often lose the context because the emit happens outside the request that registered the listener.

For those cases, capture the context when you register the callback and re-enter it when the callback fires, using bind() or an explicit run(). Do this deliberately for cross-context handoffs, and test that a queue worker processing a job still sees the originating request’s trace id, because that is the context that makes the job’s logs findable.

// Bind the store into a callback that runs later, in another context.
const handler = requestContext.bind((job: Job) => {
  // inside here the original request context is restored
  logInfo('job processed', { jobId: job.id });
});

eventBus.on('job', handler);        // registered within the request
// later, when the event fires, handler still sees the request context

Performance and Memory

AsyncLocalStorage has a small cost per store creation and per async resource, and it retains the store for the lifetime of the async context. Creating a store for a high-frequency microtask can add up, so seed it once per request rather than per operation. Keeping the store small matters more than the number of contexts.

Do not put large objects or per-call data in the store. Put identifiers and small immutable values there; large payloads belong in arguments. A store that holds a request body or a database transaction object couples the store to deep internals and keeps memory alive longer than needed.

Prefer a frozen context object so accidental writes throw in strict mode instead of silently diverging between the code that set the value and the code that reads it. A context that is read in a hundred places is not a good place to hide mutable state, because nothing enforces who may change it or when.

Common Pitfalls and Conclusion

Do not read the store outside a run() and assume it is populated. Do not mutate the context after seeding. Do not rely on propagation through an event emitter without binding. Do not store heavy objects. And do not use AsyncLocalStorage to pass data in place of a real parameter when the data is genuinely part of the function’s contract; the store is for ambient context, not for everything.

AsyncLocalStorage threads request context through arbitrary async code without polluting signatures and without the data races of globals. Seed it once at the boundary, read it in leaf code for logging and tracing, bind it across callbacks that cross async contexts, and keep it small. It is the mechanism that makes request-scoped logging and tracing practical in Node.js.

Sources: Node.js: AsyncLocalStorage, Node.js: async_hooks, OpenTelemetry: Context propagation.

FAQ

Is AsyncLocalStorage safe with concurrent requests?
Yes. Each async execution context has its own store, inherited by the promises and timers it starts. Two overlapping requests have two independent stores, which is exactly how it avoids the data race of a global variable.
Why does my context disappear in an event emitter callback?
Because the callback runs later, outside the async context that registered the listener. Capture the context when registering with bind(), or re-enter it with run() in the callback, so the store is restored when the callback fires.

Related Examples