javascript / intermediate
Snippet
Request Tracing with AsyncLocalStorage
AsyncLocalStorage maintains state across asynchronous call chains. In Node.js, this is commonly used to store request-specific context like Correlation IDs without passing them through every function.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { AsyncLocalStorage } from 'node:async_hooks';const storage = new AsyncLocalStorage();function logWithId(msg) {const id = storage.getStore()?.requestId;console.log(`[${id || 'N/A'}] ${msg}`);}storage.run({ requestId: 'abc-123' }, () => {setTimeout(() => logWithId('Finished processing'), 100);});
nodejs
Breakdown
1
storage.run(context, callback)
Sets the context for the duration of the callback, including async steps inside it.
2
storage.getStore()
Retrieves the current store associated with the execution context.