ADR 0013 — Request Context Capture via AsyncLocalStorage Middleware
Status: Accepted (★ new; pattern borrowed from drizzle-audit)
Context
Section titled “Context”Every audit event wants the same request context: actor, IP, user agent, request id, sometimes
tenant. Threading it through every call site is noisy and error-prone. drizzle-audit solved this
with an AsyncLocalStorage context and per-framework middleware.
Decision
Section titled “Decision”@xtandard/audit/contextexportsrunWithAuditContext(ctx, fn),getAuditContext(),setAuditContext(patch)(enterWith-style) andauditContextFromRequest(request, opts)(IP fromx-forwarded-for/cf-connecting-ip/x-real-ipbehind atrustProxyswitch, user agent,x-request-id). It usesnode:async_hooks(Bun, Node, Deno, Cloudflare Workers withnodejs_compat).core.record()merges the ambient context under explicit input (explicit wins) when the core is created withcontext: true(default) — the hot path stays one call.- Each framework adapter subpath exports, next to
auditPanel, anauditContext({ actor, tenant })middleware that resolves the actor/tenant from the host’s own auth and opens the scope.
Consequences
Section titled “Consequences”- One line of middleware gives every event IP/UA/request id/actor attribution.
- Runtimes without AsyncLocalStorage still work by passing
contextexplicitly.