What is async context tracking in Node.js?
Answer
Async context tracking allows you to maintain contextual data (like a request ID, user info, or trace ID) across asynchronous boundaries without passing it as function parameters. In synchronous code, you could use a global variable, but async code jumps between different contexts. AsyncLocalStorage (introduced in Node.js 12.17 as a stable API) solves this: const { AsyncLocalStorage } = require("async_hooks"); const storage = new AsyncLocalStorage();. Start a context: storage.run({ requestId: uuid() }, () => { /* all async code here can access the store */ });. Access anywhere in the async chain: const ctx = storage.getStore(); ctx.requestId;. Common uses: (1) Request-scoped logging: automatically include request ID in every log line without thread-locals; (2) Distributed tracing: propagate trace context through async operations; (3) Per-request database transactions. AsyncLocalStorage replaced the older, lower-level async_hooks API which was complex and had significant performance overhead. Express.js example: in a middleware, create the store with storage.run({ requestId: req.id }, () => next()).
Previous
What is NestJS and how does it differ from Express?
Next
What is OpenTelemetry and how is it used in Node.js?
More Node.js Questions
View all →- Advanced How does Node.js handle concurrency without multiple threads?
- Advanced What is the Node.js memory model and how does garbage collection work?
- Advanced What are memory leaks in Node.js and how do you detect them?
- Advanced What is the difference between process.exit() and throwing an uncaught exception?
- Advanced What is the N+1 query problem and how do you solve it in Node.js?