javascript / expert
Snippet
Verteilte Kontextweitergabe mit AsyncLocalStorage
AsyncLocalStorage ermöglicht das Speichern von Daten über die gesamte Lebensdauer einer asynchronen Ressource hinweg. In Next.js ist dies unersetzlich, um an den Request gebundene Metadaten (wie Trace-IDs oder Mandanten-Infos) tief im Call-Stack zu verfolgen, ohne Props manuell durch Server Components oder Actions durchreichen zu müssen.
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
Erklärung
1
new AsyncLocalStorage<Map<string, any>>();
Initialisiert einen Speichercontainer für asynchronen Kontext.
2
requestContext.run(context, fn);
Führt eine Funktion in einem begrenzten Kontext aus und stellt sicher, dass alle nachfolgenden asynchronen Aufrufe Zugriff darauf haben.
3
requestContext.getStore();
Ruft den aktuellen Kontextspeicher für den aktiven asynchronen Zweig ab.