Correlation ID Async Context
Propagate a correlation id across async calls with AsyncLocalStorage so every log line carries the request identity.
Code
import { AsyncLocalStorage } from 'node:async_hooks';
import { randomUUID } from 'node:crypto';
export const context = new AsyncLocalStorage();
export function withCorrelationId(id, fn) {
const correlationId = id || randomUUID();
return context.run({ correlationId }, fn);
}
export function currentCorrelationId() {
const store = context.getStore();
return store ? store.correlationId : undefined;
}
export function log(level, message, extra = {}) {
const correlationId = currentCorrelationId();
const record = { level, message, correlationId, ...extra };
process.stdout.write(JSON.stringify(record) + '\n');
}What the code does
Count the functions withCorrelationId, currentCorrelationId and log as the entire surface area of Correlation ID Async Context.
AsyncLocalStorage, randomUUID come from node:async_hooks, node:crypto — Node.js core modules the runtime ships with.
What to watch for
node:async_hooksis a Node.js built-in module — it ships with the runtime, so there is nothing to install.- This is browser-side code —
cryptowill not resolve in Node.
Applying it
The primary signature is export const context =
Callers only need context — everything else stays internal.
Statements that matter
process.stdout.write(JSON.stringify(record) + '\n');
return store ? store.correlationId : undefined;
return context.run({ correlationId }, fn);
Interactive Tools for This Topic
FAQ
- Does this require external packages?
- No — `node:async_hooks` is a Node.js built-in module; nothing to install.
Report a problem with this exampleOpens a pre-filled issue on GitHub.