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.
npm install async-context-storeNode.js 18.16 or newer is required.
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"),
});
});
});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()returnsundefinedoutside 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.
Node recommends AsyncLocalStorage for context propagation. It provides the
runtime integration while this package adds a typed API and explicit isolation
semantics on top.
npm install
npm run check
npm test
npm run format:checkMIT