Skip to content
jshacks.dev
Node.js

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.

1 min read
Summarize in AI

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.

request-id.mjsJavaScript
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');
Text
[req-a] start
[req-b] start
[req-b] loaded user 2
[req-b] end
[req-a] loaded user 1
[req-a] end
[-] outside any request

context.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().

Taggednode 24
Share

More snippets

Testing

Group tests with describe in node test

Group related tests with describe and it from node:test, nest suites, and run setup with beforeEach, all without installing a framework.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.