Node.js › Advanced Node.js
What is the AsyncLocalStorage API, and what problem does it solve for tracking context across asynchronous calls?
AdvancedAnswer
AsyncLocalStorage (from node:async_hooks) lets you store and retrieve data that stays associated with a single asynchronous execution chain (like one HTTP request) without needing to explicitly pass that data through every function call in between -- it's commonly used to propagate a request ID or user context through logging and downstream calls, replacing older, more fragile approaches to context propagation.
const { AsyncLocalStorage } = require('node:async_hooks');
const als = new AsyncLocalStorage();
app.use((req, res, next) => {
als.run({ requestId: crypto.randomUUID() }, next);
});
function log(message) {
const store = als.getStore();
console.log(`[${store?.requestId}] ${message}`);
}Real-world example A microservice attaches a unique request ID to every incoming request using AsyncLocalStorage, so that every log line emitted anywhere in that request's async call chain -- database queries, downstream API calls, error handlers -- automatically includes the same request ID without threading it through every function signature.