javascript / expert
Snippet
Distributed Context Propagation with AsyncLocalStorage
AsyncLocalStorage allows you to store data throughout the lifetime of an asynchronous resource. In Next.js, this is invaluable for tracking request-bound metadata (like trace IDs or tenant info) deep within the call stack without manual prop-drilling through Server Components or Actions.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { AsyncLocalStorage } from 'node:async_hooks';const requestContext = new AsyncLocalStorage<Map<string, any>>();export async function withRequestContext(context: Map<string, any>, fn: () => Promise<any>) {return requestContext.run(context, fn);}export function getFromRequest(key: string) {const store = requestContext.getStore();return store?.get(key);}
nextjs
Breakdown
1
new AsyncLocalStorage<Map<string, any>>();
Initializes a storage container for asynchronous context.
2
requestContext.run(context, fn);
Executes a function within a scoped context, ensuring all subsequent async calls have access to it.
3
requestContext.getStore();
Retrieves the current context store for the active asynchronous branch.