Skip to the content

Get started

Install the library, then configure Vite, Babel, webpack or Node.js. The build tools guide has the other tools.

Install the package

npm install async-browser-context

The package has these entries:

EntryWhat it gives
async-browser-contextAsyncLocalStorage, AsyncContext, Variable, Snapshot and addCallbackHook. On Node.js, the node export condition selects the Node.js entry.
async-browser-context/browserThe browser entry, also on Node.js.
async-browser-context/runtimeThe runtime functions of transformed code. Do not import them in your code. On Node.js, the node export condition selects the runtime of the Node.js entry.
async-browser-context/browser/runtimeThe browser runtime, also on Node.js. Use it as the runtime option together with async-browser-context/browser.
async-browser-context/opentelemetryThe OpenTelemetry context manager AsyncContextManager. It needs @opentelemetry/api.
async-browser-context/babel-presetThe Babel preset.
async-browser-context/viteThe Vite plugin asyncContext().

Configure Vite

  1. Import asyncContext from async-browser-context/vite.
  2. Add asyncContext() to the plugins list of vite.config.ts.
import { defineConfig } from "vite";
import { asyncContext } from "async-browser-context/vite";

export default defineConfig({
    plugins : [asyncContext()],
});

The plugin operates after the other plugins, so it gets JavaScript after Vite compiles TypeScript and JSX. By default, it transforms the modules of the application and the modules in node_modules. It also transforms the JavaScript of Vue, Svelte, Astro and MDX components. The API reference gives the options.

Configure Babel

  1. Add async-browser-context/babel-preset to the presets list of your Babel configuration.
  2. Put the preset last in the list. Babel uses the presets in reverse order, so the last preset operates first.
  3. For TypeScript and JSX files, add @babel/preset-typescript and @babel/preset-react before the preset of the library. Babel cannot read these files without them.
// babel.config.js
export default {
    presets : [
        "@babel/preset-env",
        "@babel/preset-react",
        "@babel/preset-typescript",
        "async-browser-context/babel-preset",
    ],
};

The preset operates with Babel 7.22 and later, and with Babel 8. It changes using and await using declarations only with Babel 7.23.9 and later.

CautionDependencies

Make sure that Babel also transforms your dependencies. Code without the transform cannot get the context of a different operation, but after its own native await it gets no context. The boundaries page gives the tools for that code.

Configure webpack

  1. Use babel-loader for all JavaScript and TypeScript files.
  2. Do not exclude node_modules, so that the loader also transforms the dependencies.
  3. Put the preset of the library last in the presets list. For TypeScript and JSX files, add @babel/preset-typescript and @babel/preset-react before it.
// webpack.config.js
export default {
    module : {
        rules : [{
            test : /\.[cm]?[jt]sx?$/,
            use : {
                loader : "babel-loader",
                options : {
                    presets : [
                        "@babel/preset-env",
                        "@babel/preset-react",
                        "@babel/preset-typescript",
                        "async-browser-context/babel-preset",
                    ],
                },
            },
        }],
    },
};

Other build tools

The build tools guide shows the setup for Rspack, Rollup, esbuild, Next.js and SWC. A test in CI builds and examines each setup.

Use Node.js

Import the package as usual. On Node.js, the node export condition selects the Node.js entry. That entry uses the native AsyncLocalStorage of node:async_hooks, and it installs no patch. A transform is not necessary on Node.js, except for rule C5. A generator keeps the context of its creation only in code that the preset transforms.

The Node.js entry and the browser entry have the same API. Thus, code that uses the library can operate in the browser and on the server.

Note

The package needs Node.js 22.18 or a later version of Node.js 22, or Node.js 24.11 or later. These versions are the versions of Babel 8.

Use the API

AsyncLocalStorage is the API of Node.js:

import { AsyncLocalStorage } from "async-browser-context";

const storage = new AsyncLocalStorage<{ requestId : string }>();

await storage.run({ requestId : "r-1" }, async () => {
    await fetch("/api/data");
    console.log(storage.getStore()?.requestId); // "r-1"
});

AsyncContext.Variable is the API of the TC39 proposal:

import { AsyncContext } from "async-browser-context";

const requestId = new AsyncContext.Variable<string>({ name : "requestId" });

await requestId.run("r-1", async () => {
    await new Promise((resolve) => setTimeout(resolve, 10));
    console.log(requestId.get()); // "r-1"
});

Use TypeScript

The package contains its type declarations. The two entries have the same types. get() and getStore() give T | undefined. Code outside a context gets the default value, and without a defaultValue option, the default value is undefined.

TypeScript finds the types with the moduleResolution settings node10, node16, nodenext and bundler. The settings node16, nodenext and bundler read the exports of package.json. For node10, the default of module: commonjs, the fields types and typesVersions give the same declaration files.

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.