AsyncLocalStorage
Background
Section titled “Background”Cloudflare Workers provides an implementation of a subset of the Node.js AsyncLocalStorage
↗ API for creating in-memory stores that remain coherent through asynchronous operations.
Constructor
Section titled “Constructor”import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
-
new AsyncLocalStorage()
: AsyncLocalStorage- Returns a new
AsyncLocalStorage
instance.
- Returns a new
Methods
Section titled “Methods”-
getStore()
: any- Returns the current store. If called outside of an asynchronous context initialized by calling
asyncLocalStorage.run()
, it returnsundefined
.
- Returns the current store. If called outside of an asynchronous context initialized by calling
-
run(storeany, callbackfunction, ...argsarguments)
: any- Runs 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 byrun()
also.
- Runs 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
-
exit(callbackfunction, ...argsarguments)
: any- Runs a function synchronously outside of a context and returns its return value. This method is equivalent to calling
run()
with thestore
value set toundefined
.
- Runs a function synchronously outside of a context and returns its return value. This method is equivalent to calling
Static Methods
Section titled “Static Methods”-
AsyncLocalStorage.bind(fn)
: function- Captures the asynchronous context that is current when
bind()
is called and returns a function that enters that context before calling the passed in function.
- Captures the asynchronous context that is current when
-
AsyncLocalStorage.snapshot()
: function- Captures the asynchronous context that is current when
snapshot()
is called and returns a function that enters that context before calling a given function.
- Captures the asynchronous context that is current when
Examples
Section titled “Examples”Fetch Listener
Section titled “Fetch Listener”import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();let idSeq = 0;
export default { async fetch(req) { return asyncLocalStorage.run(idSeq++, () => { // Simulate some async activity... await scheduler.wait(1000); return new Response(asyncLocalStorage.getStore()); }); }};
Multiple stores
Section titled “Multiple stores”The API supports multiple AsyncLocalStorage
instances to be used concurrently.
import { AsyncLocalStorage } from 'node:async_hooks';
const als1 = new AsyncLocalStorage();const als2 = new AsyncLocalStorage();
export default { async fetch(req) { return als1.run(123, () => { return als2.run(321, () => { // Simulate some async activity... await scheduler.wait(1000); return new Response(`${als1.getStore()}-${als2.getStore()}`); }); }); }};
Unhandled Rejections
Section titled “Unhandled Rejections”When a Promise
rejects and the rejection is unhandled, the async context propagates to the 'unhandledrejection'
event handler:
import { AsyncLocalStorage } from 'node:async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();let idSeq = 0;
addEventListener('unhandledrejection', (event) => { console.log(asyncLocalStorage.getStore(), 'unhandled rejection!');});
export default { async fetch(req) { return asyncLocalStorage.run(idSeq++, () => { // Cause an unhandled rejection! throw new Error('boom'); }); }};
AsyncLocalStorage.bind()
and AsyncLocalStorage.snapshot()
Section titled “AsyncLocalStorage.bind() and AsyncLocalStorage.snapshot()”import { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage();
function foo() { console.log(als.getStore()); }function bar() { console.log(als.getStore()); }
const oneFoo = als.run(123, () => AsyncLocalStorage.bind(foo));oneFoo(); // prints 123
const snapshot = als.run('abc', () => AsyncLocalStorage.snapshot());snapshot(foo); // prints 'abc'snapshot(bar); // prints 'abc'
import { AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage();
class MyResource { #runInAsyncScope = AsyncLocalStorage.snapshot();
doSomething() { this.#runInAsyncScope(() => { return als.getStore(); }); }};
const myResource = als.run(123, () => new MyResource());console.log(myResource.doSomething()); // prints 123
AsyncResource
Section titled “AsyncResource”The AsyncResource
↗ class is a component of Node.js' async context tracking API that allows users to create their own async contexts. Objects that extend from AsyncResource
are capable of propagating the async context in much the same way as promises.
Note that AsyncLocalStorage.snapshot()
and AsyncLocalStorage.bind()
provide a better approach. AsyncResource
is provided solely for backwards compatibility with Node.js.
Constructor
Section titled “Constructor”import { AsyncResource, AsyncLocalStorage } from 'node:async_hooks';
const als = new AsyncLocalStorage();
class MyResource extends AsyncResource { constructor() { // The type string is required by Node.js but unused in Workers. super('MyResource'); }
doSomething() { this.runInAsyncScope(() => { return als.getStore(); }); }};
const myResource = als.run(123, () => new MyResource());console.log(myResource.doSomething()); // prints 123
-
new AsyncResource(typestring, optionsAsyncResourceOptions)
: AsyncResource- Returns a new
AsyncResource
. Importantly, while the constructor arguments are required in Node.js' implementation ofAsyncResource
, they are not used in Workers.
- Returns a new
-
AsyncResource.bind(fnfunction, typestring, thisArgany)
- Binds the given function to the current async context.
Methods
Section titled “Methods”-
asyncResource.bind(fnfunction, thisArgany)
- Binds the given function to the async context associated with this
AsyncResource
.
- Binds the given function to the async context associated with this
-
asyncResource.runInAsyncScope(fnfunction, thisArgany, ...argsarguments)
- Call the provided function with the given arguments in the async context associated with this
AsyncResource
.
- Call the provided function with the given arguments in the async context associated with this
Caveats
Section titled “Caveats”-
The
AsyncLocalStorage
implementation provided by Workers intentionally omits support for theasyncLocalStorage.enterWith()
↗ andasyncLocalStorage.disable()
↗ methods. -
Workers does not implement the full
async_hooks
↗ API upon which Node.js' implementation ofAsyncLocalStorage
is built. -
Workers does not implement the ability to create an
AsyncResource
with an explicitly identified trigger context as allowed by Node.js. This means that a newAsyncResource
will always be bound to the async context in which it was created. -
Thenables (non-Promise objects that expose a
then()
method) are not fully supported when usingAsyncLocalStorage
. When working with thenables, instead useAsyncLocalStorage.snapshot()
↗ to capture a snapshot of the current context.
Was this helpful?
- Resources
- API
- New to Cloudflare?
- Products
- Sponsorships
- Open Source
- Support
- Help Center
- System Status
- Compliance
- GDPR
- Company
- cloudflare.com
- Our team
- Careers
- 2025 Cloudflare, Inc.
- Privacy Policy
- Terms of Use
- Report Security Issues
- Trademark