Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 133 ยท Asynchronous Programming

AsyncLocalStorage and Context

Learn AsyncLocalStorage in Node.js - run and getStore, request-scoped context, correlation IDs in logs, nested stores, snapshot and bind, pitfalls and a diagnostics_channel preview.

Imagine a server handling many requests at once. Each request has its own user, its own correlation ID, its own start time. Somewhere deep in your code, three function calls away from the request handler, you want to write a log line that includes that correlation ID. How does that function know which request it is working for?

The obvious answer is to pass a context argument through every function. That works, but it clutters every signature, and a library you did not write cannot be taught to pass it along. Other languages use "thread-local" variables for this. Node.js has one thread, and thousands of interleaved async operations on it, so thread-locals make no sense. Node's answer is AsyncLocalStorage: storage that follows the asynchronous flow of your code, through await, timers, promises and callbacks, so that code started inside one request only ever sees that request's data.

This lesson shows how it works, how to use it for request context and logging, and the traps. It builds on Promises in Depth, The Event Loop and Events and EventEmitter.

The basics: run and getStore

Create one AsyncLocalStorage instance, usually at module level. Call als.run(store, callback) to execute callback with store attached. Anywhere inside that callback, and in everything it starts asynchronously, als.getStore() returns that same value. Outside any run, it returns undefined.

Node.js run() makes a value available to everything inside

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

showUser takes no parameters, yet it prints the right user inside run and falls back to (no context) outside. The value is attached to the execution of the callback, not to the function.

Surviving async boundaries

The magic is that the store follows asynchronous work. It survives await, setTimeout, promise callbacks, process.nextTick and I/O callbacks. And two run calls going on at the same time never see each other's value, even though they interleave on the single thread.

Node.js Two interleaved flows keep separate stores

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at the output: every line shows the name of the job that printed it, even though the two jobs take turns. If the steps were plain global variables, job B would overwrite job A's value and the output would be wrong. Interleaving order between concurrent flows depends on timing, so a real program should not depend on it; what is guaranteed is that each flow reads its own store.

Request context and correlation IDs

The classic use is logging. A small log function reads the context so that every line carries the request's ID, and none of your business functions need to know about it.

Node.js A logger that adds the request ID automatically

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a real HTTP server you would call requestContext.run(...) once, in the first piece of middleware, around the rest of the handling (see Middleware Pattern). Everything after that, including your database calls, sees the same ID. For production logging patterns see Logging and Observability.

Generate IDs with crypto.randomUUID() in a real server, or honour an incoming X-Request-Id header so one ID follows a request across several services. The demo above uses a counter only so that the output is repeatable.

What the store can be

The store can be any value: a string, an object, a Map. Objects are the usual choice because you can attach more data as the request goes on. Note that run stores the reference, so mutating the object is visible to every function in the same flow.

Node.js A mutable store collects data during the flow

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Mutable context is convenient but behaves like a global within its flow, so keep it small and well named. If you want immutability, replace the store on a new run call instead of mutating it.

Nesting and exit

Calling run inside another run creates an inner scope with its own store; when the inner callback ends, the outer store is visible again. als.exit(callback) runs a callback with no store, which is useful for background work that must not inherit the request's context.

Node.js Nested run and exit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Pitfalls

Reading the store where there is none

getStore() returns undefined when no run is active: in startup code, in a timer created before the first request, in an event that originated elsewhere. Code that assumes a store will crash with a confusing error.

Node.js Forgetting that the store can be missing (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The result is TypeError: Cannot read properties of undefined (reading 'requestId'). The fix is to handle the missing case on purpose: als.getStore()?.requestId ?? 'none'. A logger should keep working outside a request.

Callbacks that run in someone else's context

Context follows the code that scheduled the work. With most APIs that is what you want. But a callback registered on a shared object (an event emitter, a connection pool, a queue) runs in the context of whoever triggers it, which may not be the context that registered it. The listener below was registered inside one run, but runs inside the one that calls emit.

Node.js Event listeners see the emitter's context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The same effect appears with connection pools: a pooled connection that was opened during request 1 may call its callbacks from the context of request 2. Libraries solve it with AsyncResource or by capturing context explicitly.

Capturing context: bind and snapshot

Two helpers let you carry context somewhere it would otherwise be lost. AsyncLocalStorage.bind(fn) returns a function that always runs in the context that was active when you called bind. AsyncLocalStorage.snapshot() returns a function that runs any callback inside the captured context.

Node.js bind and snapshot capture the current context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

enterWith: use with care

als.enterWith(store) sets the store for the rest of the current synchronous execution and everything it starts, without a callback. It is easy to leak context this way, because nothing marks where the scope ends. Prefer run. The one place enterWith is justified is a framework hook that cannot wrap the rest of the work in a callback.

Other things to remember

  • Performance. Async context tracking costs a little on every async operation. In modern Node (24) the cost is small and AsyncLocalStorage is fine for per-request context, but do not create thousands of instances or put huge objects in the store.
  • One instance per concern. Keep separate AsyncLocalStorage objects for separate things (request context, transaction, tracing) rather than one big bag.
  • Not a place for application state. Use it for ambient, per-flow metadata. Business data should still be passed as arguments.
  • Tests. Tests that run code outside run see no store, which usually shows a bug in how the code handles the missing context.

async_hooks and diagnostics_channel: a short tour

AsyncLocalStorage lives in the node:async_hooks module, whose older, lower-level createHook() API reports the birth, start and end of every async resource. Do not use createHook() for application code: it is slow and its status is experimental. AsyncResource is the supported lower-level tool for library authors who wrap their own queues or pools; it lets you say "run this callback in the context that was current when I was created".

A neighbouring tool is diagnostics_channel: named channels that libraries publish events to, and that observability tools subscribe to without the library depending on them. Publishing to a channel with no subscribers is nearly free.

Node.js diagnostics_channel publish and subscribe

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node's own http, net and fetch publish diagnostic channels too, and tracing tools use them together with AsyncLocalStorage to follow a request across your whole program. Debugging and Diagnostics shows more.

When to use it, and when not to

Use AsyncLocalStorage for cross-cutting context you would otherwise thread through every call: request IDs, authenticated user, tenant, transaction handles, tracing spans, locale. Avoid it when a plain function argument is clear enough: explicit parameters are easier to read, test and refactor. If a function silently needs ambient state to work, document that, and make it fail with a clear message when the store is missing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does als.getStore() return when no als.run() is active?

    Outside any run(), getStore() returns undefined. Code should handle that case, for example with optional chaining.
  2. 2. Two requests are handled at the same time, each inside its own als.run(). What does each one read with getStore()?

    The store follows the asynchronous flow, so interleaved flows on the single thread stay isolated from each other.
  3. 3. An event listener is registered inside one run() but the event is emitted inside another. Which store does the listener see by default?

    Listeners run synchronously in the context of the emit call. Use AsyncLocalStorage.bind() to pin the registration context.
  4. 4. What does als.exit(callback) do?

    exit() runs the callback outside the current context, which is useful for background work that should not inherit request data.
  5. 5. Why is run() usually preferred over enterWith()?

    enterWith() changes the store for the rest of the current execution with no visible end, which makes accidental leaks easy.

Summary

  • AsyncLocalStorage gives code an ambient, per-flow value without passing parameters through every function.
  • als.run(store, fn) sets the store for fn and everything it starts asynchronously; als.getStore() reads it, and returns undefined outside a run.
  • Interleaved flows stay isolated, which makes it ideal for request IDs, users, transactions and tracing.
  • Callbacks on shared objects run in the context of the caller that triggers them; use AsyncLocalStorage.bind() or snapshot() to capture context.
  • Prefer run over enterWith, keep stores small, and always handle the "no store" case.
  • diagnostics_channel lets libraries publish events that tools subscribe to; async_hooks.createHook() is a low-level tool you should avoid.

Next: TCP Servers and Clients with net