Add request IDs to logs with AsyncLocalStorage
Tag every log line with its request ID in Node.js 24 using AsyncLocalStorage from node:async_hooks, without passing the ID through every function call.
Two requests interleave and their log lines mix. Passing a request id through every function call fixes it and makes every signature uglier. AsyncLocalStorage carries the id along the async call chain for you.
import { AsyncLocalStorage } from 'node:async_hooks';
const context = new AsyncLocalStorage();
const log = (msg) => console.log(`[${context.getStore()?.requestId ?? '-'}] ${msg}`);
async function loadUser(id) {
await new Promise((r) => setTimeout(r, id === 1 ? 20 : 5));
log(`loaded user ${id}`);
}
function handle(requestId, userId) {
return context.run({ requestId }, async () => {
log('start');
await loadUser(userId);
log('end');
});
}
await Promise.all([handle('req-a', 1), handle('req-b', 2)]);
log('outside any request');[req-a] start
[req-b] start
[req-b] loaded user 2
[req-b] end
[req-a] loaded user 1
[req-a] end
[-] outside any requestcontext.run(store, fn) makes store visible to everything fn starts, including callbacks after await and timers, and getStore() reads it from anywhere in that chain. The two requests overlap, yet each line carries its own id, and loadUser never sees an id parameter. Outside run, the store is undefined. See AsyncLocalStorage.
Store a small object and treat it as read-only. Context can be lost across code that queues callbacks by hand, such as some older connection pools; wrap those callbacks with AsyncLocalStorage.bind. In an HTTP server, call run at the top of the request handler with an id from the incoming x-request-id header or crypto.randomUUID().