This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: nextjs-15-async-request-context-als-leak-guardrail

Next.js 15 Async Request Context & AsyncLocalStorage Isolation Standard

Enforces strict isolation of Node.js AsyncLocalStorage (ALS) and Next.js 15 dynamic asynchronous request boundaries during concurrent React Server Component (RSC) streaming renders. Prevents cross-request telemetry contamination, cryptographic context bleed, and tenant credential mixing caused by un-scoped ALS contexts, module-level singletons, and microtask interleaving.

Prohibited Anti-Pattern: Global Module-Level State and Unbounded AsyncLocalStorage Execution Leaking Across Interleaved Streaming RSC Render Passes

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Async Request Context & AsyncLocalStorage Isolation Standard - Enforces strict isolation of Node.js AsyncLocalStorage (ALS) and Next.js 15 dynamic asynchronous request boundaries during concurrent React Server Component (RSC) streaming renders. Prevents cross-request telemetry contamination, cryptographic context bleed, and tenant credential mixing caused by un-scoped ALS contexts, module-level singletons, and microtask interleaving.
globs: app/**/*.{ts,tsx}, src/app/**/*.{ts,tsx}, lib/**/*.{ts,tsx}, src/lib/**/*.{ts,tsx}, middleware.ts, src/middleware.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-async-request-context-als-leak-guardrail"
---

# Next.js 15 Async Request Context & AsyncLocalStorage Isolation Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Global Module-Level State and Unbounded AsyncLocalStorage Execution Leaking Across Interleaved Streaming RSC Render Passes

## System Constraints
You are a Principal Software Architect enforcing the Next.js 15 Async Request Context & AsyncLocalStorage Isolation Standard. You must prevent cross-tenant and cross-request state contamination in concurrent, streaming React Server Component (RSC) environments. Next.js 15 converts dynamic request APIs (cookies, headers, params, searchParams) to Promises. You must reject any module-level mutable variables, uncontained AsyncLocalStorage.enterWith() invocations, and fire-and-forget background promises that omit explicit execution context binding. Mandate React cache() for request-lifetime memoization and strict, immutable AsyncLocalStorage.run() scope enforcement.

## Strict Guidelines
- Engineers MUST ALWAYS isolate request-specific cryptographic nonces, tenant IDs, and telemetry spans using immutable context wrappers executed via AsyncLocalStorage.run() or per-request React.cache() singletons.
- Engineers MUST NOT invoke AsyncLocalStorage.enterWith() in Next.js Server Components, Server Actions, Route Handlers, or Middleware, as it permanently mutates the V8 execution context across asynchronous boundaries and bleeds state across interleaved RSC streams.
- Engineers MUST NOT store per-request telemetry, authentication tokens, or tenancy data in module-scoped variables or outer-closure singletons.
- Code MUST explicitly await all Next.js 15 dynamic APIs (e.g., await headers(), await cookies()) before capturing context state to guarantee proper subscription to the current request's asynchronous boundary.
- Services that dispatch asynchronous background tasks or detached promises from within an RSC render pass MUST capture the active ALS store snapshot using AsyncLocalStorage.bind() or run within an explicitly re-entered boundary.
- Components NEVER reassign or mutate the value returned from an AsyncLocalStorage.getStore() call; stores MUST be treated as strictly read-only and deeply frozen.

## Bad vs Good Implementations
### Module-Level Mutable State vs React cache() with AsyncLocalStorage.run Isolation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: AsyncLocalStorage.enterWith() mutates the current execution resource transition permanently, which in Node.js/Next.js streaming environments causes subsequent microtasks and interleaved RSC components from different HTTP requests to read the mutated context. The fallback to the mutable module-level variable globalActiveTenant guarantees cross-tenant state bleed under load.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';

interface RequestContext {
  tenantId: string;
  traceId: string;
  signingKey: string;
}

// ANTI-PATTERN: Module-level singleton and enterWith() bleed across concurrent streaming chunks
export const requestContextStorage = new AsyncLocalStorage<RequestContext>();
let globalActiveTenant = 'default';

export async function initContext(tenantId: string, traceId: string, signingKey: string) {
  globalActiveTenant = tenantId;
  // enterWith leaks context past the async turn into concurrent RSC render passes
  requestContextStorage.enterWith({ tenantId, traceId, signingKey });
}

export function getRequestContext(): RequestContext {
  const store = requestContextStorage.getStore();
  if (!store) {
    return { tenantId: globalActiveTenant, traceId: 'unknown', signingKey: 'fallback' };
  }
  return store;
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes React.cache() to tie context resolution directly to the Next.js 15 request lifecycle, safely awaiting dynamic headers(). The context object is deeply frozen, and AsyncLocalStorage.run() is enforced to guarantee strict stack/scope containment with zero global mutation or cross-request pollution.
```typescript
import { AsyncLocalStorage } from 'node:async_hooks';
import { cache } from 'react';
import { headers } from 'next/headers';

export interface RequestContext {
  readonly tenantId: string;
  readonly traceId: string;
  readonly signingKey: string;
}

const asyncLocalStorage = new AsyncLocalStorage<RequestContext>();

/**
 * React.cache() guarantees reference stability per-request tree in Next.js 15 RSC.
 * Dynamic APIs (headers(), cookies()) are awaited to establish the dynamic boundary.
 */
export const getRequestContext = cache(async (): Promise<RequestContext> => {
  const headerList = await headers();
  const tenantId = headerList.get('x-tenant-id');
  const traceId = headerList.get('x-trace-id') ?? crypto.randomUUID();

  if (!tenantId) {
    throw new Error('Tenant context isolation failure: Missing required header');
  }

  const context: RequestContext = Object.freeze({
    tenantId,
    traceId,
    signingKey: crypto.createHash('sha256').update(tenantId).digest('hex'),
  });

  return context;
});

/**
 * Strictly scoped execution boundary for external service calls or background dispatches.
 */
export async function withRequestContext<T>(
  context: RequestContext,
  fn: () => Promise<T>
): Promise<T> {
  return asyncLocalStorage.run(context, fn);
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Next.js 15 Async Request Context & AsyncLocalStorage Isolation Standard

Next.js 15 Async Request Context & AsyncLocalStorage Isolation Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict isolation of Node.js AsyncLocalStorage (ALS) and Next.js 15 dynamic asynchronous request boundaries during concurrent React Server Component (RSC) streaming renders. Prevents cross-request telemetry contamination, cryptographic context bleed, and tenant credential mixing caused by un-scoped ALS contexts, module-level singletons, and microtask interleaving. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Global Module-Level State and Unbounded AsyncLocalStorage Execution Leaking Across Interleaved Streaming RSC Render Passes Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftGlobal Module-Level State and Unbounded AsyncLocalStorage Execution Leaking Across Interleaved Streaming RSC Render PassesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS isolate request-specific cryptographic nonces, tenant IDs, and telemetry spans using immutable context wrappers executed via AsyncLocalStorage.run() or per-request React.cache() singletons.

Engineers MUST ALWAYS isolate request-specific cryptographic nonces, tenant IDs, and telemetry spans using immutable context wrappers executed via AsyncLocalStorage.run() or per-request React.cache() singletons.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT invoke AsyncLocalStorage.enterWith() in Next.js Server Components, Server Actions, Route Handlers, or Middleware, as it permanently mutates the V8 execution context across asynchronous boundaries and bleeds state across interleaved RSC streams.

Engineers MUST NOT invoke AsyncLocalStorage.enterWith() in Next.js Server Components, Server Actions, Route Handlers, or Middleware, as it permanently mutates the V8 execution context across asynchronous boundaries and bleeds state across interleaved RSC streams.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST NOT store per-request telemetry, authentication tokens, or tenancy data in module-scoped variables or outer-closure singletons.

Engineers MUST NOT store per-request telemetry, authentication tokens, or tenancy data in module-scoped variables or outer-closure singletons.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Code MUST explicitly await all Next.js 15 dynamic APIs (e.g., await headers(), await cookies()) before capturing context state to guarantee proper subscription to the current request's asynchronous boundary.

Code MUST explicitly await all Next.js 15 dynamic APIs (e.g., await headers(), await cookies()) before capturing context state to guarantee proper subscription to the current request's asynchronous boundary.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Services that dispatch asynchronous background tasks or detached promises from within an RSC render pass MUST capture the active ALS store snapshot using AsyncLocalStorage.bind() or run within an explicitly re-entered boundary.

Services that dispatch asynchronous background tasks or detached promises from within an RSC render pass MUST capture the active ALS store snapshot using AsyncLocalStorage.bind() or run within an explicitly re-entered boundary.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Components NEVER reassign or mutate the value returned from an AsyncLocalStorage.getStore() call

Components NEVER reassign or mutate the value returned from an AsyncLocalStorage.getStore() call; stores MUST be treated as strictly read-only and deeply frozen.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Next.js 15 Async Request Context & AsyncLocalStorage Isolation Standard critical for AI coding assistants?

Enforces strict isolation of Node.js AsyncLocalStorage (ALS) and Next.js 15 dynamic asynchronous request boundaries during concurrent React Server Component (RSC) streaming renders. Prevents cross-request telemetry contamination, cryptographic context bleed, and tenant credential mixing caused by un-scoped ALS contexts, module-level singletons, and microtask interleaving. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Global Module-Level State and Unbounded AsyncLocalStorage Execution Leaking Across Interleaved Streaming RSC Render Passes) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Next.js