Skip to the content

API reference

Each class, method and option of the library, with its type.

The entry async-browser-context gives the same API in the browser and on Node.js. In the browser, the entry installs the patches of the runtime when it loads.

AsyncContext

const AsyncContext : {
    readonly Variable : typeof Variable;
    readonly Snapshot : typeof Snapshot;
};

The namespace object of the TC39 AsyncContext proposal. AsyncContext.Variable is the same class as Variable, and AsyncContext.Snapshot is the same class as Snapshot.

Variable

class Variable<T> {
    constructor(options? : { name? : string; defaultValue? : T });
    get name() : string;
    get() : T | undefined;
    run<R, A extends unknown[]>(value : T, fn : (...args : A) => R, ...args : A) : R;
}

A value that is different in each context. This class is AsyncContext.Variable of the TC39 proposal.

MemberWhat it does
constructor(options)name is for debug tools only. The default is the empty string. defaultValue is the value outside a context.
nameThe name of the variable.
get()Gives the value of the variable in the current context, or the default value.
run(value, fn, ...args)Starts fn with args in a new context in which get() gives value. The this value of fn is undefined. Gives the result of fn. After fn, the previous context is current again.

AsyncVariable is another name for Variable. Object.prototype.toString gives [object AsyncContext.Variable] for a variable, as in the TC39 draft.

On Node.js, all Variable objects share one native AsyncLocalStorage. A Variable for each request thus does not make the async operations of Node.js 22 slower.

Snapshot

class Snapshot {
    constructor();
    run<R, A extends unknown[]>(fn : (...args : A) => R, ...args : A) : R;
    static wrap<T, A extends unknown[], R>(fn : (this : T, ...args : A) => R) : (this : T, ...args : A) => R;
}

A record of the current context. This class is AsyncContext.Snapshot of the TC39 proposal.

MemberWhat it does
constructor()Records the current context.
run(fn, ...args)Starts fn with args in the recorded context. The this value of fn is undefined. Gives the result of fn.
Snapshot.wrap(fn)Records the current context and gives a wrapper of fn. The wrapper starts fn in the recorded context, with its this value and its arguments. The name of the wrapper is wrapped and the name of fn, for example "wrapped save", and its length is the length of fn. If fn is not a function, wrap throws a TypeError.

AsyncSnapshot is another name for Snapshot. Object.prototype.toString gives [object AsyncContext.Snapshot] for a snapshot, as in the TC39 draft.

AsyncLocalStorage

class AsyncLocalStorage<T> {
    constructor(options? : { defaultValue? : T; name? : string });
    get name() : string;
    getStore() : T | undefined;
    run<R, A extends unknown[]>(store : T, callback : (...args : A) => R, ...args : A) : R;
    exit<R, A extends unknown[]>(callback : (...args : A) => R, ...args : A) : R;
    enterWith(store : T) : void;
    disable() : void;
    static bind<T, A extends unknown[], R>(fn : (this : T, ...args : A) => R) : (this : T, ...args : A) => R;
    static snapshot() : <R, A extends unknown[]>(fn : (...args : A) => R, ...args : A) => R;
}

The class of node:async_hooks, for browsers. On Node.js, the package gives the native class.

MemberWhat it does
constructor(options)The options of Node.js 24: defaultValue and name.
getStore()Gives the store of the current context. Outside run(), it gives the defaultValue of the options, or undefined. After disable(), it gives undefined.
run(store, callback, ...args)Starts callback in a new context in which getStore() gives store.
exit(callback, ...args)Starts callback in a new context in which getStore() gives undefined.
enterWith(store)Sets store for the rest of the current step, and for the code that this step starts later.
disable()getStore() gives undefined until the next run() or enterWith().
AsyncLocalStorage.bind(fn)The same as Snapshot.wrap(fn).
AsyncLocalStorage.snapshot()Records the current context and gives a function that starts a function in that context.

CautionenterWith()

Use run() if possible. enterWith() operates as on Node.js, so it can change the store of other code. In the synchronous part of an async function, it also changes the store of the caller, until the end of the step of the caller.

enterWith() outside all run() calls, for example at the top level of a module, sets a default store. No code sets the root context again, as on Node.js. Thus the store stays after a top-level await, and the callbacks that the later code registers get it. This has these effects in the browser:

  • Between tasks, the current context is not the root context (rule C1).
  • Rule C13 handles the default store as the root context. An event that the browser dispatches, or that code of the default store dispatches, gives the registration context to each listener.
  • Code without the transform also gets the default store after its native await.

A timer or a then callback that the code registered before the enterWith() keeps the context of its registration.

addCallbackHook

import { addCallbackHook, type CallbackHook } from "async-browser-context";

interface CallbackHook {
    before?(callback : Function, source : string) : void;
    after?(callback : Function, source : string) : void;
}

function addCallbackHook(hook : CallbackHook) : () => void;

Adds a hook. The library starts the hook methods before and after each callback that it starts. The function gives a function that removes the hook. The guide Find the operation of a long task shows a use.

The library starts the hook methods for these callbacks:

  • The callbacks of the patched APIs.
  • Each step of a transformed async function or async generator after an await. The first step is a direct call, thus it does not start the hook methods.
ArgumentValue
callbackThe function that the library starts. For an event listener object, it is the handleEvent method. For a step after an await, it is the body of the async function or the async generator, with its name.
sourceThe API that got the callback. The next table gives the values.
Callbacksource
Timer and scheduler callbacksThe name of the function, for example "setTimeout", "requestAnimationFrame" or "Scheduler.postTask"
then callbacks, also of catch, finally and the combinators"Promise.then"
Event listeners"addEventListener:" and the event type, for example "addEventListener:click"
on... propertiesThe name of the property, for example "onclick"
ObserversThe name of the class, for example "MutationObserver"
StreamsThe class and the method, for example "ReadableStream.pull"
Other callback APIsThe class and the method, for example "LockManager.request" or "Element.startViewTransition"
Steps after an await"await"

The rules of the hooks:

  • before and after operate in the context of the callback. Thus, getStore() and get() give the values of the callback.
  • before uses the order of registration. after uses the opposite order.
  • The library starts after also when the callback throws an error.
  • A hook cannot change the context of the callback.
  • An error in a hook goes to reportError(). An error of a getter of a hook method, or of reportError() itself, also stops at the hook. The callback operates as usual.
  • A callback that starts synchronously in a hook does not start the hook methods.
  • A callback that a hook schedules, for example a timer, a then callback or an event listener, does not start the hook methods, also later. Thus a hook cannot start itself without end.
  • Snapshot.run(), Snapshot.wrap(), AsyncLocalStorage.bind() and AsyncLocalStorage.snapshot() do not start the hook methods. Your code starts these functions.

The patches of version 0.1 of the library do not start the hooks. If a copy of version 0.1 installed some patches before this copy, addCallbackHook() writes a warning on the console one time.

On Node.js, addCallbackHook() does nothing, because the library does not wrap callbacks there. On Node.js, use node:diagnostics_channel or node:async_hooks.

NoteCost

Without a hook, each callback reads one more property. With hooks, each callback starts each hook method. Keep the hook methods short.

AsyncContextManager

import { AsyncContextManager } from "async-browser-context/opentelemetry";

provider.register({ contextManager : new AsyncContextManager() });

The OpenTelemetry ContextManager of the library. It keeps the active context with AsyncLocalStorage, also after await in transformed code. bind(context, target) binds a function, an EventTarget or a Node.js EventEmitter. It needs the package @opentelemetry/api. The guide OpenTelemetry without zone.js tells more.

The Vite plugin

import { asyncContext } from "async-browser-context/vite";

function asyncContext(options? : {
    include? : RegExp | ((id : string) => boolean);
    exclude? : RegExp | ((id : string) => boolean);
    runtime? : string;
    names? : boolean;
    ssr? : boolean;
}) : Plugin;

The plugin applies the Babel preset to each JavaScript and TypeScript module, and to the JavaScript of Vue, Svelte, Astro and MDX components. It does not transform styles. It operates after the other plugins (enforce: "post").

OptionDefaultWhat it does
includeAll modules, also in node_modulesThe modules to transform. The filter can select only from the modules above.
excludeNo moduleThe modules not to transform.
runtime"async-browser-context/runtime"The module that the transformed code imports.
namestrueGive the name of each async function to the callback hooks. The option of the preset tells more.
ssrfalseAlso transform the modules of server-side rendering. On Node.js, the native AsyncLocalStorage keeps the context, so the default is false. Set it to true for tests in the Node.js environment of Vitest.

The plugin does not change a module that has no async function, no generator and no for await loop. It does not transform the runtime of the library. The plugin skips the files in the dist folder of the package, and the preset skips the functions with the directive of the runtime. The preset also does not change the server code of React Server Components: a file or a function with the directive "use server", "use cache" or "use cache: <kind>".

The plugin gives Babel the source type "module", because Vite serves each module as an ES module, also a worker. Only a .cjs or .cts file, or a file with CommonJS marks and no static import or export, can be a script. The plugin does not read an input source map, because the map of Vite describes the code that the plugin gets. It keeps the format of large modules (compact: false).

The Babel preset

presets : [["async-browser-context/babel-preset", { runtime : "async-browser-context/runtime" }]];
OptionDefaultWhat it does
runtime"async-browser-context/runtime"The module that the transformed code imports. It must export the six names of the runtime.
namestrueGive the name of each async function and async generator to the runtime, for the callback hooks. With false, the code is smaller, and the hooks get no name for the steps after an await.

The preset operates with Babel 7.22 and later and with Babel 8. Put it last in the presets list. The preset changes using and await using declarations only with Babel 7.23.9 and later. The transform page gives the nine plugins of the preset.

The preset gives the name of each async function to coroutine, for example _coroutine(function* () {...}, "load"). It gives the name of each async generator to asyncGenerator in the same way. The callback hooks show this name for the steps after an await. A minifier does not change this name, because it is a string. The names add 0.1 to 1.8 percent to the gzip size of code with async functions (size).

The build tools guide shows the preset in webpack, Rspack, Rollup, esbuild and Next.js.

The runtime

async-browser-context/runtime exports the six names that the transformed code imports:

ExportWhat it does
coroutineOperates the generator of a transformed async function.
bindGeneratorBinds a generator object to the context of its creation (rule C5).
asyncGeneratorMakes the async generator objects of a transformed async generator. It replaces the wrapAsyncGenerator helper of Babel.
OverloadYieldThe class of the values that the body of an async generator gives for an await and for a step of yield*.
awaitAsyncGeneratorThe Babel helper of an await in an async generator.
asyncGeneratorDelegateThe Babel helper of yield* in an async generator.

Do not use them in your code. The transform page tells what they do. On Node.js, the node export condition selects a runtime with the same exports, for the native AsyncLocalStorage.

async-browser-context: AsyncLocalStorage and the TC39 AsyncContext API for browsers. The source code is on GitHub.

To change a page, edit its file in site/content/. The writing style guide tells you how.

An AI model (Claude, from Anthropic) wrote most of the text and the code of this site and of the library, under the direction of the author. The tests and the STE linter examine them.