This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: rr7-hydration-single-fetch-guardrail

React Router 7 Framework Mode: Hydration Boundaries & Single-Fetch Invariants

Enforces deterministic hydration and data synchronization across React Router 7 Framework Mode route boundaries. Eliminates hydration mismatches, double-fetch waterfalls, and serialization de-optimizations caused by legacy Remix abstractions, uncoordinated clientLoader execution, and unpinned typegen contracts.

Prohibited Anti-Pattern: Bypassing Route Typegen and Mishandling clientLoader Hydration Under Single-Fetch Streaming

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Router 7 Framework Mode: Hydration Boundaries & Single-Fetch Invariants - Enforces deterministic hydration and data synchronization across React Router 7 Framework Mode route boundaries. Eliminates hydration mismatches, double-fetch waterfalls, and serialization de-optimizations caused by legacy Remix abstractions, uncoordinated clientLoader execution, and unpinned typegen contracts.
globs: app/**/*.{ts,tsx}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/rr7-hydration-single-fetch-guardrail"
---

# React Router 7 Framework Mode: Hydration Boundaries & Single-Fetch Invariants

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Bypassing Route Typegen and Mishandling clientLoader Hydration Under Single-Fetch Streaming

## System Constraints
You are a Principal Software Architect enforcing React Router 7 Framework Mode hydration safety, Single-Fetch turbo-stream serialization, and auto-generated route module typing invariants. You must prevent hydration mismatches, superfluous client-side re-fetches, legacy Remix json() calls, and broken clientLoader.hydrate contracts.

## Strict Guidelines
- Engineers MUST ALWAYS import typed interfaces directly from the relative './+types/{route_file}' typegen target (e.g., 'Route.ComponentProps', 'Route.LoaderArgs', 'Route.ClientLoaderArgs') instead of manually defining loader generics or importing legacy Remix types.
- Engineers MUST NOT wrap loader and action returns in legacy 'json()' or 'defer()' helpers; React Router 7 Single Fetch natively serializes naked JavaScript objects, Promises, Dates, Errors, and BigInt via turbo-stream.
- Engineers MUST explicitly export 'clientLoader.hydrate = true' ONLY when client-side cache population or local synchronization must supersede or augment server-rendered SSR data during initial page load.
- When 'clientLoader' is defined alongside a server 'loader', the clientLoader MUST call 'await serverLoader()' when reading the initial server stream, preventing unintentional duplicate network round-trips.
- If a route defines 'clientLoader.hydrate = true' without immediately resolving data, the module MUST export a 'HydrateFallback' component to prevent React SSR client DOM mismatch exceptions.
- Components NEVER conditionally render browser-only APIs (such as window.localStorage or window.matchMedia) during the initial hydration pass without synchronizing through 'useSyncExternalStore' or a post-hydration 'useEffect' gate.

## Bad vs Good Implementations
### React Router 7 Route Module with Single Fetch Hydration and Typegen

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Uses deprecated json() wrapper, omits RR7 Route module typegen, triggers a duplicate client-side fetch on hydration without awaiting serverLoader(), and lacks a HydrateFallback component while declaring clientLoader.hydrate = true.
```typescript
// app/routes/dashboard.tsx
import { json } from "@remix-run/node"; // DEPRECATED in RR7 Framework Mode
import { useLoaderData } from "@remix-run/react";

export async function loader() {
  const user = await fetchUser();
  // ANTI-PATTERN: Wrapping in json() de-optimizes RR7 turbo-stream single-fetch
  return json({ user, timestamp: new Date() });
}

// ANTI-PATTERN: clientLoader re-runs on hydration without calling serverLoader,
// causing a duplicate fetch and clobbering streamed server HTML
export async function clientLoader() {
  const res = await fetch("/api/user");
  return { user: await res.json(), timestamp: new Date() };
}
// ANTI-PATTERN: clientLoader.hydrate enabled without HydrateFallback
clientLoader.hydrate = true;

export default function Dashboard() {
  // ANTI-PATTERN: Manual typeof casting loses single-fetch turbo-stream types
  const data = useLoaderData<typeof loader>();
  return (
    <div>
      {/* ANTI-PATTERN: Mismatch on initial render between SSR string and client timestamp */}
      <h1>{data.user.name} - {data.timestamp.toISOString()}</h1>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Implements typed Route module contracts via './+types/dashboard', returns bare objects and raw promises for turbo-stream single-fetch, synchronizes clientLoader with serverLoader() to prevent network waterfalls, and defines a robust HydrateFallback.
```typescript
// app/routes/dashboard.tsx
import { Suspense } from "react";
import { Await } from "react-router";
import type { Route } from "./+types/dashboard";

export async function loader({ request }: Route.LoaderArgs) {
  const userPromise = fetchUser(request);
  const meta = { serverRenderedAt: new Date() };

  // Single Fetch: return raw objects and deferred promises directly
  return { userPromise, meta };
}

export async function clientLoader({ serverLoader }: Route.ClientLoaderArgs) {
  // Coordinate with server loader to consume turbo-streamed payload without duplicate round-trip
  const serverData = await serverLoader();
  const cachedPrefs = window.localStorage.getItem("user_prefs");

  return {
    ...serverData,
    clientPrefs: cachedPrefs ? JSON.parse(cachedPrefs) : null,
  };
}
// Invariant: clientLoader.hydrate is explicitly declared when intercepting initial hydration
clientLoader.hydrate = true as const;

export function HydrateFallback() {
  return <div className="skeleton-loader" aria-busy="true">Loading session...</div>;
}

export default function Dashboard({ loaderData }: Route.ComponentProps) {
  return (
    <main>
      <h1>Session Meta: {loaderData.meta.serverRenderedAt.toISOString()}</h1>
      <Suspense fallback={<p>Streaming user profile...</p>}>
        <Await resolve={loaderData.userPromise}>
          {(user) => <p>Welcome, {user.name}!</p>}
        </Await>
      </Suspense>
    </main>
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

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

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: React Router 7 Framework Mode: Hydration Boundaries & Single-Fetch Invariants

React Router 7 Framework Mode: Hydration Boundaries & Single-Fetch Invariants defines an industrial-grade behavioral standard for frontend engineering. Enforces deterministic hydration and data synchronization across React Router 7 Framework Mode route boundaries. Eliminates hydration mismatches, double-fetch waterfalls, and serialization de-optimizations caused by legacy Remix abstractions, uncoordinated clientLoader execution, and unpinned typegen contracts. 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: Bypassing Route Typegen and Mishandling clientLoader Hydration Under Single-Fetch Streaming 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 DriftBypassing Route Typegen and Mishandling clientLoader Hydration Under Single-Fetch StreamingCritical
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 import typed interfaces directly from the relative './+types/{route_file}' typegen target (e.g., 'Route.ComponentProps', 'Route.LoaderArgs', 'Route.ClientLoaderArgs') instead of manually defining loader generics or importing legacy Remix types.

Engineers MUST ALWAYS import typed interfaces directly from the relative './+types/{route_file}' typegen target (e.g., 'Route.ComponentProps', 'Route.LoaderArgs', 'Route.ClientLoaderArgs') instead of manually defining loader generics or importing legacy Remix types.

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 wrap loader and action returns in legacy 'json()' or 'defer()' helpers

Engineers MUST NOT wrap loader and action returns in legacy 'json()' or 'defer()' helpers; React Router 7 Single Fetch natively serializes naked JavaScript objects, Promises, Dates, Errors, and BigInt via turbo-stream.

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 explicitly export 'clientLoader.hydrate = true' ONLY when client-side cache population or local synchronization must supersede or augment server-rendered SSR data during initial page load.

Engineers MUST explicitly export 'clientLoader.hydrate = true' ONLY when client-side cache population or local synchronization must supersede or augment server-rendered SSR data during initial page load.

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

When 'clientLoader' is defined alongside a server 'loader', the clientLoader MUST call 'await serverLoader()' when reading the initial server stream, preventing unintentional duplicate network round-trips.

When 'clientLoader' is defined alongside a server 'loader', the clientLoader MUST call 'await serverLoader()' when reading the initial server stream, preventing unintentional duplicate network round-trips.

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

If a route defines 'clientLoader.hydrate = true' without immediately resolving data, the module MUST export a 'HydrateFallback' component to prevent React SSR client DOM mismatch exceptions.

If a route defines 'clientLoader.hydrate = true' without immediately resolving data, the module MUST export a 'HydrateFallback' component to prevent React SSR client DOM mismatch exceptions.

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 conditionally render browser-only APIs (such as window.localStorage or window.matchMedia) during the initial hydration pass without synchronizing through 'useSyncExternalStore' or a post-hydration 'useEffect' gate.

Components NEVER conditionally render browser-only APIs (such as window.localStorage or window.matchMedia) during the initial hydration pass without synchronizing through 'useSyncExternalStore' or a post-hydration 'useEffect' gate.

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 React Router 7 Framework Mode: Hydration Boundaries & Single-Fetch Invariants critical for AI coding assistants?

Enforces deterministic hydration and data synchronization across React Router 7 Framework Mode route boundaries. Eliminates hydration mismatches, double-fetch waterfalls, and serialization de-optimizations caused by legacy Remix abstractions, uncoordinated clientLoader execution, and unpinned typegen contracts. 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 (Bypassing Route Typegen and Mishandling clientLoader Hydration Under Single-Fetch Streaming) 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

React