AsyncLocalStorage
This class creates stores that stay coherent through asynchronous operations.
Interface AsyncLocalStorage
interface AsyncLocalStorage<T>This class creates stores that stay coherent through asynchronous operations.
While you can create your own implementation on top of the node:async_hooks module, AsyncLocalStorage should be preferred as it is a performant and memory
safe implementation that involves significant optimizations that are non-obvious
to implement.
The following example uses AsyncLocalStorage to build a simple logger
that assigns IDs to incoming HTTP requests and includes them in messages
logged within each request.
import http from 'node:http';
import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
console.log(`${id !== undefined ? id : '-'}:`, msg);
}
let idSeq = 0;
http.createServer((req, res) => {
asyncLocalStorage.run(idSeq++, () => {
logWithId('start');
// Imagine any chain of async operations here
setImmediate(() => {
logWithId('finish');
res.end();
});
});
}).listen(8080);
http.get('http://localhost:8080');
http.get('http://localhost:8080');
// Prints:
// 0: start
// 0: finish
// 1: start
// 1: finishEach instance of AsyncLocalStorage maintains an independent storage context.
Multiple instances can safely exist simultaneously without risk of interfering
with each other's data.
Properties
name
stringThe name of the AsyncLocalStorage instance if provided.
Methods
disable
disable(): voidDisables the instance of AsyncLocalStorage. All subsequent calls
to asyncLocalStorage.getStore() will return undefined until asyncLocalStorage.run() or asyncLocalStorage.enterWith() is called again.
When calling asyncLocalStorage.disable(), all current contexts linked to the
instance will be exited.
Calling asyncLocalStorage.disable() is required before the asyncLocalStorage can be garbage collected. This does not apply to stores
provided by the asyncLocalStorage, as those objects are garbage collected
along with the corresponding async resources.
Use this method when the asyncLocalStorage is not in use anymore
in the current process.
Returns void
enterWith
enterWith(store: T): voidTransitions into the context for the remainder of the current synchronous execution and then persists the store through any following asynchronous calls.
Example:
const store = { id: 1 };
// Replaces previous store with the given store object
asyncLocalStorage.enterWith(store);
asyncLocalStorage.getStore(); // Returns the store object
someAsyncOperation(() => {
asyncLocalStorage.getStore(); // Returns the same object
});This transition will continue for the entire synchronous execution.
This means that if, for example, the context is entered within an event
handler subsequent event handlers will also run within that context unless
specifically bound to another context with an AsyncResource. That is why run() should be preferred over enterWith() unless there are strong reasons
to use the latter method.
const store = { id: 1 };
emitter.on('my-event', () => {
asyncLocalStorage.enterWith(store);
});
emitter.on('my-event', () => {
asyncLocalStorage.getStore(); // Returns the same object
});
asyncLocalStorage.getStore(); // Returns undefined
emitter.emit('my-event');
asyncLocalStorage.getStore(); // Returns the same objectParameters
-
store: T
Returns void
exit
exit<R, TArgs extends any[]>(callback: (args: TArgs) => R, ...args: TArgs): RRuns a function synchronously outside of a context and returns its
return value. The store is not accessible within the callback function or
the asynchronous operations created within the callback. Any getStore() call done within the callback function will always return undefined.
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by exit() too.
The stacktrace is not impacted by this call and the context is re-entered.
Example:
// Within a call to run
try {
asyncLocalStorage.getStore(); // Returns the store object or value
asyncLocalStorage.exit(() => {
asyncLocalStorage.getStore(); // Returns undefined
throw new Error();
});
} catch (e) {
asyncLocalStorage.getStore(); // Returns the same object or value
// The error will be caught here
}Parameters
-
callback: (args: TArgs) => R -
...args: TArgs
Returns R
getStore
getStore(): T | undefinedReturns the current store.
If called outside of an asynchronous context initialized by
calling asyncLocalStorage.run() or asyncLocalStorage.enterWith(), it
returns undefined.
Returns T | undefined
run
run<R>(store: T, callback: () => R): RRuns a function synchronously within a context and returns its return value. The store is not accessible outside of the callback function. The store is accessible to any asynchronous operations created within the callback.
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by run() too.
The stacktrace is not impacted by this call and the context is exited.
Example:
const store = { id: 2 };
try {
asyncLocalStorage.run(store, () => {
asyncLocalStorage.getStore(); // Returns the store object
setTimeout(() => {
asyncLocalStorage.getStore(); // Returns the store object
}, 200);
throw new Error();
});
} catch (e) {
asyncLocalStorage.getStore(); // Returns undefined
// The error will be caught here
}Parameters
-
store: T -
callback: () => R
Returns R
run<R, TArgs extends any[]>(store: T, callback: (args: TArgs) => R, ...args: TArgs): RRuns a function synchronously within a context and returns its return value. The store is not accessible outside of the callback function. The store is accessible to any asynchronous operations created within the callback.
The optional args are passed to the callback function.
If the callback function throws an error, the error is thrown by run() too.
The stacktrace is not impacted by this call and the context is exited.
Example:
const store = { id: 2 };
try {
asyncLocalStorage.run(store, () => {
asyncLocalStorage.getStore(); // Returns the store object
setTimeout(() => {
asyncLocalStorage.getStore(); // Returns the store object
}, 200);
throw new Error();
});
} catch (e) {
asyncLocalStorage.getStore(); // Returns undefined
// The error will be caught here
}Parameters
-
store: T -
callback: (args: TArgs) => R -
...args: TArgs
Returns R
withScope
withScope(store: T): RunScopeCreates a disposable scope that enters the given store and automatically
restores the previous store value when the scope is disposed. This method is
designed to work with JavaScript's explicit resource management (using syntax).
Example:
import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
{
using _ = asyncLocalStorage.withScope('my-store');
console.log(asyncLocalStorage.getStore()); // Prints: my-store
}
console.log(asyncLocalStorage.getStore()); // Prints: undefinedThe withScope() method is particularly useful for managing context in
synchronous code where you want to ensure the previous store value is restored
when exiting a block, even if an error is thrown.
import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
try {
using _ = asyncLocalStorage.withScope('my-store');
console.log(asyncLocalStorage.getStore()); // Prints: my-store
throw new Error('test');
} catch (e) {
// Store is automatically restored even after error
console.log(asyncLocalStorage.getStore()); // Prints: undefined
}Important: When using withScope() in async functions before the first
await, be aware that the scope change will affect the caller's context. The
synchronous portion of an async function (before the first await) runs
immediately when called, and when it reaches the first await, it returns the
promise to the caller. At that point, the scope change becomes visible in the
caller's context and will persist in subsequent synchronous code until something
else changes the scope value. For async operations, prefer using run() which
properly isolates context across async boundaries.
import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
async function example() {
using _ = asyncLocalStorage.withScope('my-store');
console.log(asyncLocalStorage.getStore()); // Prints: my-store
await someAsyncOperation(); // Function pauses here and returns promise
console.log(asyncLocalStorage.getStore()); // Prints: my-store
}
// Calling without await
example(); // Synchronous portion runs, then pauses at first await
// After the promise is returned, the scope 'my-store' is now active in caller!
console.log(asyncLocalStorage.getStore()); // Prints: my-store (unexpected!)Parameters
-
store: T
Returns RunScope