Skip to content

Repository files navigation

async-context-store

Typed, isolated async context for Node.js.

async-context-store gives asynchronous work a small, explicit context that flows through promises, timers, and callbacks. It is built on Node's AsyncLocalStorage and keeps child contexts isolated from their parents and sibling operations.

Install

npm install async-context-store

Node.js 18.16 or newer is required.

Usage

import { createContextStore } from "async-context-store";

type RequestContext = {
  requestId: string;
  accountId?: string;
  operation?: string;
};

const context = createContextStore<RequestContext>();

await context.run({ requestId: "req-123" }, async () => {
  await context.with({ accountId: "account-456" }, async () => {
    await saveAuditLog({
      requestId: context.get("requestId"),
      accountId: context.get("accountId"),
    });
  });
});

Contract

  • run(context, callback) creates a root context.
  • with(patch, callback) creates an isolated child context.
  • Context values propagate through asynchronous work created inside the callback.
  • A child patch never changes its parent or sibling contexts.
  • get() returns undefined outside a context; require() throws instead.
  • Context objects are shallow-copied and frozen by the store. Keep nested values immutable when isolation matters.
  • snapshot() binds the current context to a callback that can run later.

The package intentionally has no ambient set() method. Mutating a shared store makes concurrent branches observe one another's values. Use with() to make the ownership and lifetime of a context change visible.

Why not raw async_hooks?

Node recommends AsyncLocalStorage for context propagation. It provides the runtime integration while this package adds a typed API and explicit isolation semantics on top.

Development

npm install
npm run check
npm test
npm run format:check

License

MIT

About

Typed, isolated async context for Node.js

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages