Skip to content

.tip

ยท one of the small things

AsyncLocalStorage carries the request id for you

Passing a request id through every function signature gets old by the third layer. AsyncLocalStorage keeps it in the async context instead.

import { AsyncLocalStorage } from "node:async_hooks";
 
const store = new AsyncLocalStorage<{ requestId: string }>();
app.use((req, _res, next) => store.run({ requestId: crypto.randomUUID() }, next));
// below: store.getStore()?.requestId

The store follows awaits inside that call tree and nowhere else, so concurrent requests never read each other's value. Set it at the edge and the logger picks it up.

nodejsobservability