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

React Router 7 Framework Mode: Hydration, Single Fetch, and Route Module Typegen Invariants

In React Router 7 Framework Mode, data boundaries rely on Single Fetch architecture backed by turbo-stream serialization and auto-generated route module typegen. Violating hydration lifecycle invariants—such as wrapping naked data returns in legacy Response objects, neglecting clientLoader.hydrate execution semantics, or discarding generated Route types—triggers hydration mismatches, tears down streaming boundaries, and breaks isomorphic rendering.

Prohibited Anti-Pattern: Bypassing Single Fetch Wire Serialization and Misconfiguring clientLoader.hydrate Lifecycle Boundaries

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Router 7 Framework Mode: Hydration, Single Fetch, and Route Module Typegen Invariants - In React Router 7 Framework Mode, data boundaries rely on Single Fetch architecture backed by turbo-stream serialization and auto-generated route module typegen. Violating hydration lifecycle invariants—such as wrapping naked data returns in legacy Response objects, neglecting clientLoader.hydrate execution semantics, or discarding generated Route types—triggers hydration mismatches, tears down streaming boundaries, and breaks isomorphic rendering.
globs: app/**/+types/**/*.{ts,tsx}, app/routes/**/*.{ts,tsx}, app/root.tsx
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-router-v7-framework-hydration-single-fetch"
---

# React Router 7 Framework Mode: Hydration, Single Fetch, and Route Module Typegen Invariants

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Bypassing Single Fetch Wire Serialization and Misconfiguring clientLoader.hydrate Lifecycle Boundaries

## System Constraints
You are a Principal Software Architect enforcing React Router 7 Framework Mode hydration safety, Single Fetch streaming contracts, and route module typegen. Reject legacy Remix v2 json() wrappers, enforce explicit clientLoader.hydrate contracts, require strict use of ./+types relative imports, and ensure all streaming promises are consumed via Suspense and Await boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS import Route module types strictly from the auto-generated relative path `./+types/<route-filename-without-ext>` to guarantee complete LoaderData, ActionData, and Params synchronization.
- Engineers MUST NOT wrap loader returns in `json()` or `new Response(JSON.stringify(...))` under React Router 7 Single Fetch; naked objects, native instances (`Date`, `BigInt`, `Map`, `Set`, `Error`), and deferred `Promise` instances MUST be returned directly.
- Engineers MUST explicitly set `clientLoader.hydrate = true` if and only if the `clientLoader` is intended to execute during initial SSR document hydration; otherwise, omitting it instructs the runtime to consume serverLoader output without executing clientLoader on the initial load.
- Code SHOULD leverage `serverLoader()` inside `clientLoader` when decorating, caching, or augmenting SSR payloads on the client to avoid redundant network fetch waterfalls.
- Components NEVER render client-specific primitives (e.g., localStorage, window.matchMedia) during the initial hydration pass; non-deterministic values MUST be deferred to `useEffect` or client-only gates to avoid React hydration mismatch crashes.

## Bad vs Good Implementations
### React Router 7 Loader and ClientLoader Hydration Contract

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using legacy json() breaks Single Fetch turbo-stream serialization, turning native Date instances into strings and preventing direct streaming of promises. Omitting Route module typegen from `./+types` sacrifices compile-time route validation. Omitting `clientLoader.hydrate = true` prevents clientLoader from executing during initial page load when client-side state synchronization is required.
```typescript
import { json } from '@remix-run/node'; // Anti-pattern: Legacy Remix v2 import
import { Await, useLoaderData } from 'react-router';

// Anti-pattern: Manual parameter typing bypasses route typegen
export async function loader({ params }: { params: { id: string } }) {
  const userPromise = fetchUser(params.id);
  const timestamp = new Date();
  // Anti-pattern: json() serializes Date to string and breaks turbo-stream streaming
  return json({ userPromise, timestamp });
}

// Anti-pattern: Missing clientLoader.hydrate flag; loader will not execute on hydration,
// leading to cache inconsistency when components expect client-side state.
export async function clientLoader({ serverLoader }: any) {
  const data = await serverLoader();
  localStorage.setItem('cached-user', JSON.stringify(data));
  return data;
}

export default function RouteComponent() {
  // Anti-pattern: Untyped or manually cast loader data
  const { userPromise, timestamp } = useLoaderData() as any;

  return (
    <div>
      {/* Anti-pattern: timestamp is string due to json(), crashing if treated as Date */}
      <p>Loaded at: {timestamp.toISOString()}</p>
      <Await resolve={userPromise}>
        {(user) => <div>{user.name}</div>}
      </Await>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Employs strict Route typegen via `./+types/user-profile`. Naked objects are returned directly to let React Router 7's Single Fetch encode native data structures and streaming promises via turbo-stream. `clientLoader.hydrate = true` formally declares execution on SSR hydration, and `<Suspense>` guarantees proper boundary streaming without hydration mismatches.
```typescript
import { Suspense } from 'react';
import { Await } from 'react-router';
import type { Route } from './+types/user-profile';

export async function loader({ params }: Route.LoaderArgs) {
  const userPromise = fetchUser(params.id);
  // Direct return: Single Fetch natively preserves Date, Error, Map, Set, BigInt, and Promise
  return {
    userPromise,
    timestamp: new Date(),
  };
}

// Explicitly mandate execution during SSR hydration to warm local storage or memory cache
export async function clientLoader({ serverLoader }: Route.ClientLoaderArgs) {
  const serverData = await serverLoader();
  return {
    ...serverData,
    cachedLocally: true,
  };
}
clientLoader.hydrate = true as const;

export default function RouteComponent({ loaderData }: Route.ComponentProps) {
  const { userPromise, timestamp } = loaderData;

  return (
    <div>
      <p>Loaded at: {timestamp.toISOString()}</p>
      <Suspense fallback={<div>Loading user profile...</div>}>
        <Await resolve={userPromise}>
          {(user) => <div>{user.name}</div>}
        </Await>
      </Suspense>
    </div>
  );
}
```

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, Single Fetch, and Route Module Typegen Invariants

React Router 7 Framework Mode: Hydration, Single Fetch, and Route Module Typegen Invariants defines an industrial-grade behavioral standard for frontend engineering. In React Router 7 Framework Mode, data boundaries rely on Single Fetch architecture backed by turbo-stream serialization and auto-generated route module typegen. Violating hydration lifecycle invariants—such as wrapping naked data returns in legacy Response objects, neglecting clientLoader.hydrate execution semantics, or discarding generated Route types—triggers hydration mismatches, tears down streaming boundaries, and breaks isomorphic rendering. 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 Single Fetch Wire Serialization and Misconfiguring clientLoader.hydrate Lifecycle Boundaries 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 Single Fetch Wire Serialization and Misconfiguring clientLoader.hydrate Lifecycle BoundariesCritical
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 Route module types strictly from the auto-generated relative path `./+types/<route-filename-without-ext>` to guarantee complete LoaderData, ActionData, and Params synchronization.

Engineers MUST ALWAYS import Route module types strictly from the auto-generated relative path `./+types/<route-filename-without-ext>` to guarantee complete LoaderData, ActionData, and Params synchronization.

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 returns in `json()` or `new Response(JSON.stringify(...))` under React Router 7 Single Fetch

Engineers MUST NOT wrap loader returns in `json()` or `new Response(JSON.stringify(...))` under React Router 7 Single Fetch; naked objects, native instances (`Date`, `BigInt`, `Map`, `Set`, `Error`), and deferred `Promise` instances MUST be returned directly.

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 set `clientLoader.hydrate = true` if and only if the `clientLoader` is intended to execute during initial SSR document hydration

Engineers MUST explicitly set `clientLoader.hydrate = true` if and only if the `clientLoader` is intended to execute during initial SSR document hydration; otherwise, omitting it instructs the runtime to consume serverLoader output without executing clientLoader on the initial 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

Code SHOULD leverage `serverLoader()` inside `clientLoader` when decorating, caching, or augmenting SSR payloads on the client to avoid redundant network fetch waterfalls.

Code SHOULD leverage `serverLoader()` inside `clientLoader` when decorating, caching, or augmenting SSR payloads on the client to avoid redundant network fetch waterfalls.

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 render client-specific primitives (e.g., localStorage, window.matchMedia) during the initial hydration pass

Components NEVER render client-specific primitives (e.g., localStorage, window.matchMedia) during the initial hydration pass; non-deterministic values MUST be deferred to `useEffect` or client-only gates to avoid React hydration mismatch crashes.

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, Single Fetch, and Route Module Typegen Invariants critical for AI coding assistants?

In React Router 7 Framework Mode, data boundaries rely on Single Fetch architecture backed by turbo-stream serialization and auto-generated route module typegen. Violating hydration lifecycle invariants—such as wrapping naked data returns in legacy Response objects, neglecting clientLoader.hydrate execution semantics, or discarding generated Route types—triggers hydration mismatches, tears down streaming boundaries, and breaks isomorphic rendering. 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 Single Fetch Wire Serialization and Misconfiguring clientLoader.hydrate Lifecycle Boundaries) 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