AsyncLocalStorage: Simplify Context Management in Node.js
AsyncLocalStorage gives you a way to maintain context across your async operations without manually passing data through every function. Think of it like having a secret storage box that follows your request around, carrying important information that any part of your code can access.
Here’s what a typical Express application without AsyncLocalStorage
might look like. We need to pass the userId
through multiple functions:
async function handleRequest(req, res) {
const userId = req.headers['user-id'];
await validateUser(userId);
await processOrder(userId);
await sendNotification(userId);
}
async function validateUser(userId) {
// Need userId here
}
async function processOrder(userId) {
// Need userId here too
await updateInventory(userId);
}
async function updateInventory(userId) {
// Still need userId here
}
async function sendNotification(userId) {
// And here
}
Notice how we keep passing userId
everywhere? Now multiply this by several more parameters like requestId
, tenantId
, and locale
. The function signatures grow unwieldy fast.
Here’s how we can clean this up with AsyncLocalStorage