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

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

Enforces architectural boundaries for React Router 7 Framework Mode, specifically governing single-fetch serialization, clientLoader hydration orchestration, and strict route module typegen consumption. Prevents double-fetching cascades, turbo-stream hydration mismatches, and broken client-side streaming topologies.

Prohibited Anti-Pattern: Bypassing Route Typegen, Misusing clientLoader.hydrate Without serverLoader(), or Returning Legacy json()/defer() Under Single-Fetch

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: React Router 7 Framework Hydration, Single Fetch, and Route Typegen Invariants - Enforces architectural boundaries for React Router 7 Framework Mode, specifically governing single-fetch serialization, clientLoader hydration orchestration, and strict route module typegen consumption. Prevents double-fetching cascades, turbo-stream hydration mismatches, and broken client-side streaming topologies.
globs: app/**/*.{ts,tsx}, react-router.config.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/react-router-7-framework-hydration-boundaries"
---

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

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Bypassing Route Typegen, Misusing clientLoader.hydrate Without serverLoader(), or Returning Legacy json()/defer() Under Single-Fetch

## System Constraints
You are a Principal Frontend Architect enforcing strict React Router 7 framework-mode standards. You must mandate strict adherence to route module typegen, Single Fetch native data return patterns, clientLoader hydration coordination, and proper Turbo-stream promise boundaries.

## Strict Guidelines
- Engineers MUST ALWAYS import route types strictly from the generated './+types/<route-filename>' module (e.g., `Route.LoaderArgs`, `Route.ComponentProps`, `Route.ClientLoaderArgs`) and NEVER write manual parameter interfaces for route components or loaders.
- Engineers MUST NOT use deprecated Remix v2 serialization utilities like `json()` or `defer()`; Single Fetch requires raw JavaScript objects containing naked or nested promises returned directly or via the `data()` utility for headers/status control.
- Engineers MUST explicitly await `serverLoader()` when defining `clientLoader.hydrate = true` if the client cache does not possess the complete SSR payload, preventing race conditions, hydration flashes, and double network requests.
- Engineers MUST NEVER await streaming promises inside the `loader`; unawaited promises must be returned directly within the data payload to preserve HTTP streaming and Suspense boundary rendering.
- Components MUST wrap streaming promises accessed from `useLoaderData()` in `<Suspense>` and `<Await>` boundaries, providing a deterministic fallback that aligns with server SSR output.
- Services MUST serialize complex types (Dates, BigInt, Sets, Maps, Error instances) knowing Single Fetch Turbo-stream preserves them natively; do not manually transform Dates to ISO strings across loader boundaries.

## Bad vs Good Implementations
### Single Fetch Streaming & Route Typegen (Raw Objects & Suspense)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using legacy `defer()` breaks React Router 7 Single Fetch turbo-stream semantics. Manual interface typing bypasses the generated `./+types` file, risking type drift for loader outputs, params, and search parameters.
```typescript
import { defer } from "@remix-run/node"; // Legacy Remix anti-pattern
import { useLoaderData, Await } from "react-router";
import { Suspense } from "react";

interface LoaderData {
  criticalData: { user: string };
  streamedData: Promise<{ analytics: number }>;
}

export async function loader() {
  const criticalData = await fetchCritical();
  const streamedData = fetchSlowMetrics();
  // ANTI-PATTERN: Using deprecated defer() in RR7 single-fetch mode
  return defer({ criticalData, streamedData });
}

// ANTI-PATTERN: Manual typing without typegen, bypassing generated Route contract
export default function RouteComponent() {
  const { criticalData, streamedData } = useLoaderData() as LoaderData;
  return (
    <div>
      <h1>{criticalData.user}</h1>
      <Suspense fallback={<span>Loading...</span>}>
        <Await resolve={streamedData}>{(val) => <span>{val.analytics}</span>}</Await>
      </Suspense>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Utilizes RR7 typegen `./+types/dashboard`, passes loaderData directly via component props, returns naked promises natively handled by Single Fetch turbo-stream, and preserves native object types.
```typescript
import { Suspense } from "react";
import { Await, data } from "react-router";
import type { Route } from "./+types/dashboard";

export async function loader({ request }: Route.LoaderArgs) {
  const criticalData = await fetchCritical(request);
  // Native promise returned without awaiting allows streaming
  const streamedData = fetchSlowMetrics(request);

  // RR7 Single-Fetch: Return raw object or data() helper with headers
  return data(
    {
      criticalData,
      streamedData,
      timestamp: new Date() // Turbo-stream preserves native Date instance
    },
    { headers: { "Cache-Control": "private, max-age=60" } }
  );
}

export default function RouteComponent({ loaderData }: Route.ComponentProps) {
  return (
    <div>
      <h1>{loaderData.criticalData.user}</h1>
      <p>Fetched at: {loaderData.timestamp.toISOString()}</p>
      <Suspense fallback={<DashboardSkeleton />}>
        <Await resolve={loaderData.streamedData}>
          {(resolvedMetrics) => <span>{resolvedMetrics.analytics}</span>}
        </Await>
      </Suspense>
    </div>
  );
}
```

### clientLoader Hydration Boundary & Cache Coordination

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Setting `clientLoader.hydrate = true` without consuming `serverLoader()` causes the client to bypass or discard server-rendered data during initial page load, causing layout shifts and duplicate data queries.
```typescript
import type { Route } from "./+types/profile";
import { queryClient } from "~/lib/query";

export async function loader({ params }: Route.LoaderArgs) {
  return { profile: await fetchProfile(params.id) };
}

// ANTI-PATTERN: hydrate = true set, but ignores serverLoader()
// Causes immediate re-fetch on the client, wiping out SSR state and causing hydration flash
export async function clientLoader({ params }: Route.ClientLoaderArgs) {
  const cached = queryClient.getQueryData(["profile", params.id]);
  if (cached) return cached;
  return fetch(`/api/profile/${params.id}`).then((r) => r.json());
}
clientLoader.hydrate = true;
```

#### Production Standard (Correct)
> **Standard**: By invoking `await serverLoader()`, `clientLoader` consumes the turbo-stream payload from SSR during hydration, populates the client cache seamlessly, and prevents duplicate network waterfalls or visual flickering.
```typescript
import type { Route } from "./+types/profile";
import { queryClient } from "~/lib/query";

export async function loader({ params }: Route.LoaderArgs) {
  return { profile: await fetchProfile(params.id) };
}

// CORRECT: Coordinate client hydration with serverLoader()
export async function clientLoader({
  params,
  serverLoader
}: Route.ClientLoaderArgs) {
  const queryKey = ["profile", params.id];
  const cached = queryClient.getQueryData<Route.ComponentProps["loaderData"]>(queryKey);

  if (cached) {
    return cached;
  }

  // Hydrate the client cache directly from the server-rendered payload
  const serverData = await serverLoader();
  queryClient.setQueryData(queryKey, serverData);
  return serverData;
}

// Only opt into initial hydration run if explicitly syncing client cache state
clientLoader.hydrate = true as const;
```

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

React Router 7 Framework Hydration, Single Fetch, and Route Typegen Invariants defines an industrial-grade behavioral standard for frontend engineering. Enforces architectural boundaries for React Router 7 Framework Mode, specifically governing single-fetch serialization, clientLoader hydration orchestration, and strict route module typegen consumption. Prevents double-fetching cascades, turbo-stream hydration mismatches, and broken client-side streaming topologies. 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, Misusing clientLoader.hydrate Without serverLoader(), or Returning Legacy json()/defer() Under Single-Fetch 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, Misusing clientLoader.hydrate Without serverLoader(), or Returning Legacy json()/defer() Under Single-FetchCritical
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 types strictly from the generated './+types/<route-filename>' module (e.g., `Route.LoaderArgs`, `Route.ComponentProps`, `Route.ClientLoaderArgs`) and NEVER write manual parameter interfaces for route components or loaders.

Engineers MUST ALWAYS import route types strictly from the generated './+types/<route-filename>' module (e.g., `Route.LoaderArgs`, `Route.ComponentProps`, `Route.ClientLoaderArgs`) and NEVER write manual parameter interfaces for route components or loaders.

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 use deprecated Remix v2 serialization utilities like `json()` or `defer()`

Engineers MUST NOT use deprecated Remix v2 serialization utilities like `json()` or `defer()`; Single Fetch requires raw JavaScript objects containing naked or nested promises returned directly or via the `data()` utility for headers/status control.

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 await `serverLoader()` when defining `clientLoader.hydrate = true` if the client cache does not possess the complete SSR payload, preventing race conditions, hydration flashes, and double network requests.

Engineers MUST explicitly await `serverLoader()` when defining `clientLoader.hydrate = true` if the client cache does not possess the complete SSR payload, preventing race conditions, hydration flashes, and double network requests.

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

Engineers MUST NEVER await streaming promises inside the `loader`

Engineers MUST NEVER await streaming promises inside the `loader`; unawaited promises must be returned directly within the data payload to preserve HTTP streaming and Suspense boundary rendering.

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 MUST wrap streaming promises accessed from `useLoaderData()` in `<Suspense>` and `<Await>` boundaries, providing a deterministic fallback that aligns with server SSR output.

Components MUST wrap streaming promises accessed from `useLoaderData()` in `<Suspense>` and `<Await>` boundaries, providing a deterministic fallback that aligns with server SSR output.

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

Services MUST serialize complex types (Dates, BigInt, Sets, Maps, Error instances) knowing Single Fetch Turbo-stream preserves them natively

Services MUST serialize complex types (Dates, BigInt, Sets, Maps, Error instances) knowing Single Fetch Turbo-stream preserves them natively; do not manually transform Dates to ISO strings across loader 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.
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 Hydration, Single Fetch, and Route Typegen Invariants critical for AI coding assistants?

Enforces architectural boundaries for React Router 7 Framework Mode, specifically governing single-fetch serialization, clientLoader hydration orchestration, and strict route module typegen consumption. Prevents double-fetching cascades, turbo-stream hydration mismatches, and broken client-side streaming topologies. 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, Misusing clientLoader.hydrate Without serverLoader(), or Returning Legacy json()/defer() Under Single-Fetch) 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