This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: tanstack-start-ssr-streaming-guardrail

TanStack Start & Router: Type-Safe Search, SSR Loaders, and Deferred Streaming

Enforces strict type safety for URL search params via schema validation, mandates non-blocking SSR via TanStack Router's defer API for slow data, and guarantees reactive loader refetches using loaderDeps. Prevents SSR waterfall freezes, hydration mismatches, and stale route-state synchronization bugs.

Prohibited Anti-Pattern: Blocking SSR with monolithic awaits, unvalidated search params, and missing loaderDeps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Start & Router: Type-Safe Search, SSR Loaders, and Deferred Streaming - Enforces strict type safety for URL search params via schema validation, mandates non-blocking SSR via TanStack Router's defer API for slow data, and guarantees reactive loader refetches using loaderDeps. Prevents SSR waterfall freezes, hydration mismatches, and stale route-state synchronization bugs.
globs: src/routes/**/*.{ts,tsx}, app/routes/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tanstack-start-ssr-streaming-guardrail"
---

# TanStack Start & Router: Type-Safe Search, SSR Loaders, and Deferred Streaming

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blocking SSR with monolithic awaits, unvalidated search params, and missing loaderDeps

## System Constraints
You are a Principal Software Architect enforcing TanStack Start and TanStack Router architectural invariants. Mandate strict schema validation for all search params, explicit dependency declaration in loaderDeps, and non-blocking streaming execution using defer() and <Await> for secondary data. Reject unvalidated query strings, manual useEffect data fetching in routes, and monolithic Promise.all loader barriers that stall server response times.

## Strict Guidelines
- Engineers MUST ALWAYS validate search params using validateSearch with a standard schema library (Zod, Valibot, ArkType) via createFileRoute.
- Engineers MUST ALWAYS declare loaderDeps: ({ search }) => ({ ... }) whenever loader execution depends on validated search parameters; failing to do so causes loaders to skip re-execution on search state transitions.
- Engineers MUST NEVER block the initial SSR HTML shell with slow, non-critical database/API queries; slow promises MUST be wrapped with defer() in the loader and rendered with <Suspense> and <Await>.
- Code SHOULD differentiate between critical data (directly awaited in loader for SEO and metadata) and non-critical data (deferred to allow instantaneous TTFB).
- Services MUST execute server-side data fetching via createServerFn() from @tanstack/start to establish clean server/client boundaries.
- Components NEVER read raw window.location.search or parse URL query strings manually; they MUST consume search parameters exclusively via Route.useSearch().

## Bad vs Good Implementations
### Type-Safe Search Params, loaderDeps, and Deferred SSR Streaming

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Failing to define validateSearch eliminates type safety and runtime URL sanitization. Omitting loaderDeps means route search updates (e.g., changing ?page=2) will not re-trigger the loader. Awaiting slowAnalytics directly blocks the server response, delaying Time-to-First-Byte (TTFB) by seconds instead of streaming.
```typescript
import { createFileRoute } from '@tanstack/react-router';

// ANTI-PATTERN: No validateSearch, monolithic blocking await stalling SSR,
// missing loaderDeps so pagination changes never trigger a loader re-fetch.
export const Route = createFileRoute('/dashboard')({
  loader: async ({ location }) => {
    // Manual string parsing or ignoring search safety
    const page = Number(new URLSearchParams(location.search).get('page') || '1');

    // Monolithic blocking await: slowAnalytics blocks the entire HTML document
    const [userProfile, slowAnalytics] = await Promise.all([
      fetchUserProfile(),
      fetchSlowAnalytics(page), // Takes 2500ms; stalls TTFB
    ]);

    return { userProfile, slowAnalytics };
  },
  component: DashboardComponent,
});

function DashboardComponent() {
  const { userProfile, slowAnalytics } = Route.useLoaderData();
  return (
    <div>
      <h1>Welcome, {userProfile.name}</h1>
      <div>Analytics: {slowAnalytics.metrics}</div>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: validateSearch ensures runtime and compile-time type safety for search params. loaderDeps explicitly registers search state reactive dependencies. defer() paired with <Suspense> and <Await> enables the initial HTML document to stream immediately, drastically optimizing TTFB while background promises resolve out-of-order.
```typescript
import { createFileRoute, defer, Await } from '@tanstack/react-router';
import { Suspense } from 'react';
import { z } from 'zod';

const searchSchema = z.object({
  page: z.number().catch(1),
  filter: z.string().optional(),
});

export const Route = createFileRoute('/dashboard')({
  validateSearch: (search) => searchSchema.parse(search),
  // loaderDeps ensures loader re-fires precisely when search dependencies change
  loaderDeps: ({ search: { page, filter } }) => ({ page, filter }),
  loader: async ({ deps }) => {
    // Critical data: Awaited for immediate shell render & SEO
    const userProfile = await fetchUserProfile();

    // Non-critical data: Deferred to stream over chunked HTTP transfer
    const slowAnalytics = defer(fetchSlowAnalytics(deps.page, deps.filter));

    return {
      userProfile,
      slowAnalytics,
    };
  },
  component: DashboardComponent,
});

function DashboardComponent() {
  const { userProfile, slowAnalytics } = Route.useLoaderData();

  return (
    <div>
      <h1>Welcome, {userProfile.name}</h1>
      <Suspense fallback={<div>Loading telemetry metrics...</div>}>
        <Await promise={slowAnalytics}>
          {(analytics) => <div>Analytics: {analytics.metrics}</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: TanStack Start & Router: Type-Safe Search, SSR Loaders, and Deferred Streaming

TanStack Start & Router: Type-Safe Search, SSR Loaders, and Deferred Streaming defines an industrial-grade behavioral standard for frontend engineering. Enforces strict type safety for URL search params via schema validation, mandates non-blocking SSR via TanStack Router's defer API for slow data, and guarantees reactive loader refetches using loaderDeps. Prevents SSR waterfall freezes, hydration mismatches, and stale route-state synchronization bugs. 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: Blocking SSR with monolithic awaits, unvalidated search params, and missing loaderDeps 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 DriftBlocking SSR with monolithic awaits, unvalidated search params, and missing loaderDepsCritical
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 validate search params using validateSearch with a standard schema library (Zod, Valibot, ArkType) via createFileRoute.

Engineers MUST ALWAYS validate search params using validateSearch with a standard schema library (Zod, Valibot, ArkType) via createFileRoute.

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 ALWAYS declare loaderDeps

Engineers MUST ALWAYS declare loaderDeps: ({ search }) => ({ ... }) whenever loader execution depends on validated search parameters; failing to do so causes loaders to skip re-execution on search state transitions.

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 NEVER block the initial SSR HTML shell with slow, non-critical database/API queries

Engineers MUST NEVER block the initial SSR HTML shell with slow, non-critical database/API queries; slow promises MUST be wrapped with defer() in the loader and rendered with <Suspense> and <Await>.

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 differentiate between critical data (directly awaited in loader for SEO and metadata) and non-critical data (deferred to allow instantaneous TTFB).

Code SHOULD differentiate between critical data (directly awaited in loader for SEO and metadata) and non-critical data (deferred to allow instantaneous TTFB).

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 MUST execute server-side data fetching via createServerFn() from @tanstack/start to establish clean server/client boundaries.

Services MUST execute server-side data fetching via createServerFn() from @tanstack/start to establish clean server/client 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.
6

Components NEVER read raw window.location.search or parse URL query strings manually

Components NEVER read raw window.location.search or parse URL query strings manually; they MUST consume search parameters exclusively via Route.useSearch().

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 TanStack Start & Router: Type-Safe Search, SSR Loaders, and Deferred Streaming critical for AI coding assistants?

Enforces strict type safety for URL search params via schema validation, mandates non-blocking SSR via TanStack Router's defer API for slow data, and guarantees reactive loader refetches using loaderDeps. Prevents SSR waterfall freezes, hydration mismatches, and stale route-state synchronization bugs. 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 (Blocking SSR with monolithic awaits, unvalidated search params, and missing loaderDeps) 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

TanStack