javascript / expert
Snippet
Context-Aware Tracking with AsyncLocalStorage
AsyncLocalStorage allows persisting data across asynchronous boundaries without manual prop drilling. It is essential for tracking request-specific metadata (like correlation IDs) in complex Node.js microservices.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { AsyncLocalStorage } = require('node:async_hooks');const storage = new AsyncLocalStorage();function logWithId(msg) {const id = storage.getStore()?.requestId || 'anonymous';console.log(`[${id}] ${msg}`);}function handleRequest(reqId) {storage.run({ requestId: reqId }, () => {setImmediate(() => logWithId('Processing complete'));});}handleRequest('req-123');
nodejs
Breakdown
1
const storage = new AsyncLocalStorage();
Initializes a new storage instance to hold asynchronous context.
2
storage.getStore()?.requestId
Safely retrieves the current context from the async execution chain.
3
storage.run({ requestId: reqId }, () => { ... });
Executes a callback within a scoped context that persists through nested async calls.