This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: nextjs-15-dynamic-io-cache-determinism

Next.js 15 Dynamic I/O Cache Determinism & Uncached IO Quarantine

Enforces strict isolation between static prerenders and dynamic runtime operations under Next.js 15 Dynamic I/O (experimental.dynamicIO). Guarantees that uncached operations like raw database queries, cookies, and headers are quarantined behind explicit connection boundaries and Suspense fallbacks, while deterministic data paths leverage explicit 'use cache' directives with deterministic cacheLife and cacheTag declarations.

Prohibited Anti-Pattern: Leaking Dynamic Primitives or Uncached Async I/O into Prerenderable Component Subtrees

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Next.js 15 Dynamic I/O Cache Determinism & Uncached IO Quarantine - Enforces strict isolation between static prerenders and dynamic runtime operations under Next.js 15 Dynamic I/O (experimental.dynamicIO). Guarantees that uncached operations like raw database queries, cookies, and headers are quarantined behind explicit connection boundaries and Suspense fallbacks, while deterministic data paths leverage explicit 'use cache' directives with deterministic cacheLife and cacheTag declarations.
globs: src/app/**/*.{ts,tsx}, app/**/*.{ts,tsx}, src/lib/**/*.{ts,tsx}, lib/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/nextjs-15-dynamic-io-cache-determinism"
---

# Next.js 15 Dynamic I/O Cache Determinism & Uncached IO Quarantine

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Leaking Dynamic Primitives or Uncached Async I/O into Prerenderable Component Subtrees

## System Constraints
You are a Principal Software Architect enforcing Next.js 15 Dynamic I/O Cache Determinism and Uncached IO Quarantine. Under Dynamic I/O, any un-flagged async fetch, database query, or access to runtime context (headers, cookies, searchParams) bails the entire subtree out of static prerendering and introduces runtime hydration drift. You must enforce explicit cache boundaries: deterministic data must be wrapped in 'use cache' scopes with cacheLife and cacheTag, while dynamic runtime access must be quarantined behind await connection() inside React Suspense boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS isolate dynamic runtime primitives (cookies(), headers(), searchParams) within granular leaf components wrapped in React <Suspense> boundaries.
- Engineers MUST designate deterministic data retrieval with the 'use cache' directive at either the file, function, or component level, declaring explicit cacheLife() and cacheTag().
- Engineers MUST NOT access cookies(), headers(), or any uncached dynamic runtime API inside a 'use cache' scope.
- Code MUST explicitly call await connection() prior to executing non-deterministic or uncached I/O (e.g., real-time database transactions, geolocation checks) to signal intentional dynamic execution to the compiler.
- Components NEVER execute raw uncached I/O directly in top-level layouts or page roots without a parent Suspense boundary, preventing build-time prerender failure.

## Bad vs Good Implementations
### Uncached DB Fetch and Headers Ingestion vs. Quarantined Dynamic Connection with 'use cache'

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Mixing uncached database access with dynamic header inspection in the root component forces the entire route to opt out of prerendering. Under Next.js 15 dynamicIO, this triggers compilation errors or severe runtime performance penalties because static and dynamic concerns are completely un-quarantined.
```typescript
import { headers } from 'next/headers';
import { db } from '@/lib/db';

// Anti-pattern: Interleaving dynamic headers and direct DB I/O in the page root
// Under Dynamic I/O, this de-optimizes the entire page, prevents static generation,
// and risks hydration mismatch between prerender and dynamic request phases.
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const headerList = await headers();
  const userAgent = headerList.get('user-agent') ?? 'unknown';
  
  // Uncached DB query directly in the render path causes dynamic bailout
  const product = await db.product.findUnique({ where: { id } });
  
  return (
    <main>
      <h1>{product?.name}</h1>
      <p>Visitor UA: {userAgent}</p>
    </main>
  );
}
```

#### Production Standard (Correct)
> **Standard**: The product fetching logic is marked with 'use cache', declaring cache lifetime and tags, allowing Next.js 15 to prerender the product shell statically. The uncached header access is quarantined into a separate component using await connection() and wrapped in a React Suspense boundary, eliminating hydration drift and unintended dynamic route bailouts.
```typescript
import { Suspense } from 'react';
import { headers } from 'next/headers';
import { connection } from 'next/server';
import { unstable_cacheLife as cacheLife, unstable_cacheTag as cacheTag } from 'next/cache';
import { db } from '@/lib/db';

// Deterministic Data Access: Strictly isolated with 'use cache'
async function getProduct(id: string) {
  'use cache';
  cacheLife('hours');
  cacheTag(`product-${id}`);
  
  return await db.product.findUnique({ where: { id } });
}

// Quarantined Dynamic Leaf Component
async function DynamicUserTracker() {
  // Explicitly inform compiler this is uncached runtime I/O
  await connection();
  const headerList = await headers();
  const userAgent = headerList.get('user-agent') ?? 'unknown';
  return <p>Visitor UA: {userAgent}</p>;
}

export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const product = await getProduct(id);

  return (
    <main>
      {/* Static deterministic shell prerendered reliably */}
      <h1>{product?.name}</h1>
      
      {/* Dynamic runtime IO strictly quarantined behind Suspense boundary */}
      <Suspense fallback={<p>Loading tracker...</p>}>
        <DynamicUserTracker />
      </Suspense>
    </main>
  );
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Next.js 15 Dynamic I/O Cache Determinism & Uncached IO Quarantine

Next.js 15 Dynamic I/O Cache Determinism & Uncached IO Quarantine defines an industrial-grade behavioral standard for backend engineering. Enforces strict isolation between static prerenders and dynamic runtime operations under Next.js 15 Dynamic I/O (experimental.dynamicIO). Guarantees that uncached operations like raw database queries, cookies, and headers are quarantined behind explicit connection boundaries and Suspense fallbacks, while deterministic data paths leverage explicit 'use cache' directives with deterministic cacheLife and cacheTag declarations. 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: Leaking Dynamic Primitives or Uncached Async I/O into Prerenderable Component Subtrees 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 DriftLeaking Dynamic Primitives or Uncached Async I/O into Prerenderable Component SubtreesCritical
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 dynamic runtime primitives (cookies(), headers(), searchParams) within granular leaf components wrapped in React <Suspense> boundaries.

Engineers MUST ALWAYS isolate dynamic runtime primitives (cookies(), headers(), searchParams) within granular leaf components wrapped in React <Suspense> boundaries.

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 designate deterministic data retrieval with the 'use cache' directive at either the file, function, or component level, declaring explicit cacheLife() and cacheTag().

Engineers MUST designate deterministic data retrieval with the 'use cache' directive at either the file, function, or component level, declaring explicit cacheLife() and cacheTag().

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 access cookies(), headers(), or any uncached dynamic runtime API inside a 'use cache' scope.

Engineers MUST NOT access cookies(), headers(), or any uncached dynamic runtime API inside a 'use cache' scope.

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 call await connection() prior to executing non-deterministic or uncached I/O (e.g., real-time database transactions, geolocation checks) to signal intentional dynamic execution to the compiler.

Code MUST explicitly call await connection() prior to executing non-deterministic or uncached I/O (e.g., real-time database transactions, geolocation checks) to signal intentional dynamic execution to the compiler.

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

Components NEVER execute raw uncached I/O directly in top-level layouts or page roots without a parent Suspense boundary, preventing build-time prerender failure.

Components NEVER execute raw uncached I/O directly in top-level layouts or page roots without a parent Suspense boundary, preventing build-time prerender failure.

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 Dynamic I/O Cache Determinism & Uncached IO Quarantine critical for AI coding assistants?

Enforces strict isolation between static prerenders and dynamic runtime operations under Next.js 15 Dynamic I/O (experimental.dynamicIO). Guarantees that uncached operations like raw database queries, cookies, and headers are quarantined behind explicit connection boundaries and Suspense fallbacks, while deterministic data paths leverage explicit 'use cache' directives with deterministic cacheLife and cacheTag declarations. 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 (Leaking Dynamic Primitives or Uncached Async I/O into Prerenderable Component Subtrees) 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.

1 Rule in Stack

Next.js