Skip to content
By 15 min readUpdated

Keep Your Functions Clean & Focused: Context Provision with Node.js AsyncLocalStorage

Leverage AsyncLocalStorage to manage context provision and extend functionality without changing core code.


ℹ️

Update (October 2026): I added a short explanation of what AsyncLocalStorage is with a minimal runnable example, an Express middleware example, and notes on performance (Node.js 24 switched to AsyncContextFrame) and the TC39 AsyncContext proposal. I also fixed a few bugs in the code examples.

AsyncLocalStorage is Node.js’s built-in way to share context, like a request ID, a logger, or a database transaction, across async calls without passing it through every function. In this post, I’ll explain what it is and how run() and getStore() work. Then I’ll show two real-world use cases, database transactions and logging, and how they help you follow the Open/Closed principle.

What Is AsyncLocalStorage?

AsyncLocalStorage is a class exported from node:async_hooks and has been a stable API since Node.js 16.4. You call run(store, callback), and every function called from callback, synchronously or after any number of awaits, can read that store via getStore(). Concurrent run() calls each get their own store. Think of it as thread-local storage for async code.

import { AsyncLocalStorage } from 'node:async_hooks';
import { setTimeout } from 'node:timers/promises';
const requestContext = new AsyncLocalStorage();
function log(message) {
const requestId = requestContext.getStore()?.requestId;
console.log(`[${requestId}] ${message}`);
}
async function handleRequest() {
log('start');
await setTimeout(10); // context survives the await
log('done');
}
await Promise.all([
requestContext.run({ requestId: 'req-1' }, handleRequest),
requestContext.run({ requestId: 'req-2' }, handleRequest),
]);
log('outside run()'); // getStore() returns undefined here

Output:

[req-1] start
[req-2] start
[req-1] done
[req-2] done
[undefined] outside run()

log never receives the request ID as an argument. Outside of run(), getStore() returns undefined.

ℹ️

There is also enterWith(store), which sets the store for the rest of the current synchronous execution instead of wrapping a callback. It is marked experimental, and the Node.js docs recommend run() instead, because the context also leaks into code you didn’t intend, e.g. subsequent event handlers.

Why It’s Useful: The Open/Closed Principle

You have probably heard of the SOLID principles in programming. By applying them to your codebase, you can create a solid (🤡) architecture that is both easy to maintain and extend.

SOLID stands for:

  • Single Responsibility
  • Open/Closed
  • Liskov Substitution
  • Interface Segregation
  • Dependency Inversion

AsyncLocalStorage is a great tool to implement the Open/Closed principle.

The open/closed principle states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

But what does that mean?

I will focus on two examples to showcase how you can apply the open/closed principle using Node.js’s AsyncLocalStorage:

  1. Database transactions
  2. Logging

First, I’ll show you a violation of the open/closed principle, and then I will demonstrate how to adhere to it using Node.js’s built-in AsyncLocalStorage.

Violation of the Open/Closed Principle

Example 1: Database Transactions

Imagine you have a repository function that creates a user profile in the database.

import { db } from './db';
async function main() {
await createUserProfile({ id: '1', name: 'John Doe' });
}
async function createUserProfile(profile) {
await db.insert(userProfileTable).values(profile);
};

Alright, now suppose you want to create the user profile together with a user entity stored in a different table. You should do that in a single transaction because neither should exist without the other. This is what you might do:

import { db } from './db';
async function main() {
await db.transaction(async (transaction) => {
await Promise.all([
createUserProfile({ id: '1', name: 'John Doe' }, transaction),
createUser({ id: '1', name: 'John Doe' }, transaction),
]);
});
}
// ❌ we have added the transaction argument to the function (= extended the function)
// ❌ this violates the open/closed principle
async function createUserProfile(profile, transaction) {
await (transaction ?? db).insert(userProfileTable).values(profile);
};
async function createUser(user, transaction) {
await (transaction ?? db).insert(userTable).values(user);
}

That works, but it is a violation of the open/closed principle ❌ You are modifying the createUserProfile function to accommodate the new requirement. Every time you decide to run a repository function within a transaction, you must modify the function to pass the transaction argument.

Example 2: Logging

Imagine you have a logger with an appendKeys method that appends keys to every subsequent log statement (just like the logger from Powertools for AWS Lambda). This is very useful to find all logs that are related.

Consider a scenario where you have a function that processes an order. You want to easily find all logs related to a specific order. To achieve that, you use logger.appendKeys to append the orderId to every log statement:

import { logger } from './logger';
async function main() {
await processOrder(order);
}
async function processOrder(order) {
logger.appendKeys({ orderId: order.id });
// ...
const total = calculateOrderTotal(order.lineItems);
// ...
}
function calculateOrderTotal(lineItems) {
// calculation...
// this will also log the orderId since we have appended it to the logger instance
logger.debug('calculated order total', { total: 100 });
}

Now, suppose you want to process multiple orders concurrently. You cannot simply call appendKeys on the global logger instance because the orderId key would be overwritten, as all processOrder executions share the same logger instance.

One way to deal with this, would be to create a separate logger instance for every processOrder call:

import { logger } from './logger';
async function main() {
await Promise.all(orders.map(order => {
const childLogger = logger.createChild();
return processOrder(order, childLogger);
}));
}
// ❌ we had to add the logger argument to the function
// ❌ this violates the open/closed principle
async function processOrder(order, logger) {
logger.appendKeys({ orderId: order.id });
// ...
}

Another solution is to not use logger.appendKeys altogether and instead pass the orderId to every log statement:

import { logger } from './logger';
async function main() {
await Promise.all(orders.map(order => processOrder(order)));
}
async function processOrder(order) {
// ...
const total = calculateOrderTotal(order);
// ...
}
// ❌ we now pass the whole order because we need access to the orderId for logging
// ❌ this violates the open/closed principle
function calculateOrderTotal(order) {
// calculation...
// we have to pass the orderId explicitly in every log statement
logger.debug('calculated order total', { total: 100, orderId: order.id });
}

This approach is not only tedious but also error-prone, since you must consistently use the same orderId key in every log statement to correlate logs associated with a specific order.

You can imagine that both of these approaches quickly become unmanageable—especially when processOrder calls many other functions in a deeply nested manner.

Applying the Open/Closed Principle with AsyncLocalStorage

Now that we know what a violation of the open/closed principle looks like, let’s fix it with AsyncLocalStorage.

Context Sharing with AsyncLocalStorage

We want the createUserProfile and processOrder functions to work in different scenarios without needing to modify them. For instance, createUserProfile shouldn’t have to know whether it is running in a transaction or not, and processOrder should not change just because it is executed concurrently.

So how do we solve this?

We can leverage AsyncLocalStorage to create a context that is available to all functions executed within the same scope. This allows us to modify the behavior of functions without actually changing their implementations.

context.ts
import { AsyncLocalStorage } from 'node:async_hooks';
export function createContext<T>() {
const context = new AsyncLocalStorage<T>();
return {
use() {
const result = context.getStore();
if (result === undefined) {
throw new Error('No context available');
}
return result;
},
provide<R>(value: T, callback: () => R) {
return context.run<R>(value, callback);
},
};
}
ℹ️

I have learned about the usage of AsyncLocalStorage from the codebase of terminal.shop (the repository is no longer publicly available). This is where I took the code for createContext from and also the transaction example (not the logging example though).

createContext creates a private storage context that is only accessible within the createContext function. It returns an object with a use method that returns the current context and a provide method that allows you to provide a context (value) that is available with the callback function.

Example usage:

const userContext = createContext<{ userId: string }>();
userContext.provide({ userId: '123' }, async () => {
// this can be somewhere deeply nested in your codebase
const { userId } = userContext.use();
});
ℹ️

This is probably familiar to you if you know React. React also has useContext and createContext to provide data to (potentially deeply nested) components without having to pass props through every component.

How can we leverage the createContext function to solve our examples?

Example 1 Revisited: Database Transactions

Let’s use the createContext function to create a context for the database transaction.

type TransactionOrDb = Transaction | typeof db;
const TransactionContext = createContext<{
transaction: Transaction;
}>();
function getTransaction(): Transaction | undefined {
try {
return TransactionContext.use().transaction;
} catch {
// this throws outside of the context (see `createContext().use()`)
return undefined;
}
}
async function provideTransaction<T>(
callback: (transaction: Transaction) => Promise<T>,
transactionOptions?: TransactionOptions,
): Promise<T> {
// if there already is a transaction context, we use that
const existingTransaction = getTransaction();
if (existingTransaction) {
return callback(existingTransaction);
}
// otherwise we start a new transaction that we provide to the callback
const result = await db.transaction(
async (transaction) => {
return TransactionContext.provide({ transaction }, () => callback(transaction));
},
transactionOptions,
);
return result as T;
}
async function useTransactionOrDb<T>(callback: (transactionOrDb: TransactionOrDb) => Promise<T>) {
// if not within a context, we use the db instance
return callback(getTransaction() ?? db);
}

We have three functions that essentially wrap the use and provide methods of the createContext function:

  • getTransaction returns the current transaction or undefined outside of a transaction context. It only catches the error of a missing context, so errors thrown by your own callbacks are passed through as they are.
  • provideTransaction is used to provide a transaction to the callback function. It either uses an already existing transaction or starts a new one.
  • useTransactionOrDb returns the transaction if it is within a transaction context or the db instance otherwise.

Now, instead of using the db instance directly in our app, we can just always use useTransactionOrDb.

Back to our example, we have the following code before deciding to use a transaction:

async function main() {
await createUserProfile({ id: '1', name: 'John Doe' });
}
async function createUserProfile(profile) {
await useTransactionOrDb((tx) => tx.insert(userProfileTable).values(profile));
};

Here, createUserProfile will just use the db instance directly since it is not within a transaction context.

Now, decide that we have to run createUserProfile in a transaction together with createUser. We can do that by providing a transaction to the createUserProfile function:

async function main() {
await provideTransaction(async () => {
await Promise.all([
createUserProfile({ id: '1', name: 'John Doe' }),
createUser({ id: '1', name: 'John Doe' }),
]);
});
}
// ✅ the arguments are unchanged – no modification needed
async function createUserProfile(profile) {
await useTransactionOrDb((tx) => tx.insert(userProfileTable).values(profile));
};
async function createUser(user) {
await useTransactionOrDb((tx) => tx.insert(userTable).values(user));
}

Now we are following the open/closed principle! We did not have to modify the createUserProfile function to accommodate the new requirement. Only the caller of the function has to know about the context.

Example 2 Revisited: Logging

Now, let’s see how we can apply the open/closed principle to the logging example.

Again, we are creating some helper functions that wrap the use and provide methods of the createContext function:

const LoggerContext = createContext<{
logger: Logger;
}>();
export function createLoggerContext<T>(callback: (logger: Logger) => T): T {
// always create a new child logger, so appended keys don't leak into the parent or sibling contexts.
// it inherits all keys of the current logger (e.g. a requestId appended in an outer LoggerContext)
const childLogger = getLogger().createChild();
return LoggerContext.provide({ logger: childLogger }, () => callback(childLogger));
}
export function getLogger() {
try {
const { logger } = LoggerContext.use();
return logger;
} catch {
return logger;
}
}

This is similar to the previous example, with one difference:

  • createLoggerContext always creates a new child of the current logger and provides it to the callback function. Unlike provideTransaction, it doesn’t reuse an existing context, because every caller needs its own logger instance.
  • getLogger is used to return the logger. If there is no logger in the context, it will return the global logger.

Now we can use that to follow the open/closed principle in our second example. Instead of using the logger instance directly, just always use getLogger. This is how our initial code looks like:

import { getLogger } from './logger';
async function main() {
await processOrder(order);
}
async function processOrder(order) {
getLogger().appendKeys({ orderId: order.id });
// ...
const total = calculateOrderTotal(order.lineItems);
// ...
}
function calculateOrderTotal(lineItems) {
// calculation...
// this will also log the orderId since we have appended it to the logger instance
getLogger().debug('calculated order total', { total: 100 });
}

Okay, now we change it to run processOrder in parallel:

import { createLoggerContext, getLogger } from './logger';
async function main() {
await Promise.all(orders.map(order => {
return createLoggerContext(() => {
return processOrder(order);
});
}));
}
// ✅ the arguments are unchanged – no modification needed
async function processOrder(order) {
getLogger().appendKeys({ orderId: order.id });
// ...
const total = calculateOrderTotal(order.lineItems);
// ...
}
function calculateOrderTotal(lineItems) {
// calculation...
// this will also log the orderId since we have appended it to the logger instance
getLogger().debug('calculated order total', { total: 100 });
}

We now create a child logger for every processOrder call. processOrder can just call getLogger().appendKeys to append the orderId to the logger as it did before. Now the keys don’t overwrite each other because getLogger() returns a different child logger instance per order. This even works if main itself runs within a LoggerContext: every order gets its own child, which inherits the keys of the outer logger.

By using getLogger() throughout your codebase instead of the global logger instance, we don’t have to modify any functions if they are run differently. We are following the open/closed principle!

Using AsyncLocalStorage in Express Middleware

The most common use case is request-scoped context in a web server. In Express, call next inside run(). All following middleware and route handlers, and everything they call, run within that context:

import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
import express from 'express';
const requestContext = new AsyncLocalStorage();
const app = express();
app.use((req, res, next) => {
const requestId = req.get('x-request-id') ?? randomUUID();
requestContext.run({ requestId }, next);
});
app.get('/orders', async (req, res) => {
const orders = await listOrders(); // anything in here can call requestContext.getStore()
res.json(orders);
});

Register this middleware before everything else that needs the context. The same approach works with other frameworks: call run() as early as possible in the request lifecycle.

Performance

AsyncLocalStorage used to be built on async_hooks, which adds overhead to async operations. Node.js 22.7 added an opt-in rewrite without async_hooks, called AsyncContextFrame, that relies on a V8 feature for propagating context instead (--experimental-async-context-frame). Since Node.js 24, it is the default. The release notes describe it as “a more efficient implementation of asynchronous context tracking”. You can switch back to the old implementation with --no-async-context-frame.

I won’t give you benchmark numbers since they depend heavily on your workload, so measure in your app if it matters. In practice: call run() once per request or job with a small store object. And if you are tempted to build your own context tracking on top of async_hooks: the Node.js docs explicitly recommend AsyncLocalStorage instead.

AsyncLocalStorage vs. the TC39 AsyncContext Proposal

AsyncContext is a TC39 proposal to bring the same capability to JavaScript itself, so it works in browsers and all runtimes. At the time of writing, it is at Stage 2. The API looks very similar:

const requestContext = new AsyncContext.Variable();
requestContext.run({ requestId: 'req-1' }, async () => {
await doWork();
requestContext.get(); // { requestId: 'req-1' }
});

AsyncContext.Variable is the equivalent of an AsyncLocalStorage instance (get() instead of getStore()), and AsyncContext.Snapshot is similar to AsyncLocalStorage.snapshot(). There is no enterWith() equivalent. Node’s AsyncContextFrame rewrite was done in anticipation of this proposal. Until it lands, AsyncLocalStorage is what you use in Node.js. Wrapping it in a small helper like createContext above keeps a later switch contained to one file.

Conclusion

AsyncLocalStorage gives you a per-async-context store: set it with run(), read it with getStore() anywhere down the call chain. In this post, we have also seen how to apply the open/closed principle with it. We created a createContext function that allows us to establish a context for any type, which we then leveraged to solve our two examples.

Here are some key takeaways:

  • Decoupled Context Management: By using AsyncLocalStorage, you can inject contextual data (like transaction handles or logging metadata) without modifying the core business logic.
  • Adherence to the Open/Closed Principle: Functions remain closed for modification while still being open for extension, minimizing the need to alter function signatures as new requirements arise.
  • Elimination of Manual Parameter Drag: AsyncLocalStorage prevents the tedious and error-prone process of manually threading context through multiple function calls.
  • Improved Maintainability: By isolating context handling from your repository and logging logic, your codebase stays cleaner, more modular, and easier to maintain.
  • Enhanced Debugging and Consistency: Automatically propagated context ensures that logs and database transactions are consistent, making debugging and analytics more straightforward.
  • Versatile Application: This approach benefits various scenarios, including managing database transactions and setting up consistent logging across parallel asynchronous processes. These takeaways emphasize how leveraging Node.js AsyncLocalStorage can lead to more robust, maintainable, and scalable code while adhering to fundamental design principles.

Further Reading