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

TanStack Start SSR Invariants: Type-Safe Search Validation, Streaming Deferrals, and Loader Dependency Tracking

Enforce strict schema validation on URL search parameters via validateSearch, prevent server-side TTFB bottlenecks by mandating defer() streaming for non-critical data, and guarantee deterministic hydration through explicit loaderDeps tracking across TanStack Start routes.

Prohibited Anti-Pattern: Blocking SSR TTFB via Monolithic Loaders and Runtime Deserialization Failures via Unvalidated Search Params

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Start SSR Invariants: Type-Safe Search Validation, Streaming Deferrals, and Loader Dependency Tracking - Enforce strict schema validation on URL search parameters via validateSearch, prevent server-side TTFB bottlenecks by mandating defer() streaming for non-critical data, and guarantee deterministic hydration through explicit loaderDeps tracking across TanStack Start routes.
globs: app/**/*.{ts,tsx}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tanstack-start-ssr-streaming-params"
---

# TanStack Start SSR Invariants: Type-Safe Search Validation, Streaming Deferrals, and Loader Dependency Tracking

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blocking SSR TTFB via Monolithic Loaders and Runtime Deserialization Failures via Unvalidated Search Params

## System Constraints
You are a Principal Software Architect enforcing zero-defect TanStack Start and TanStack Router fullstack SSR architectures. You mandate compile-time and runtime validation for all search parameters, non-blocking SSR TTFB through proper use of defer() streaming with Suspense and Await components, explicit loader dependencies with loaderDeps, and strict server/client boundary hygiene using createServerFn.

## Strict Guidelines
- Engineers MUST ALWAYS validate route search parameters using standard schema parsers (e.g., Zod, Valibot) within the validateSearch route definition property to guarantee runtime safety and bidirectional type generation.
- Engineers MUST NOT block SSR Time-to-First-Byte (TTFB) by awaiting slow, non-critical asynchronous data in loaders; secondary promises MUST be wrapped in defer() and rendered client-side using TanStack Router's <Await> and React <Suspense>.
- Engineers MUST ALWAYS declare loader dependencies explicitly in loaderDeps when loader execution depends on validated search parameters; loaders MUST NOT read raw URL or untracked state directly.
- Services exposing fullstack operations MUST encapsulate Node/server-only operations in createServerFn and avoid importing server-only modules into client-consumed route files.
- Components NEVER read window.location or query parameters imperatively in components or effects; components MUST consume search parameters exclusively via useSearch() or Route.useSearch().

## Bad vs Good Implementations
### Type-Safe Search Parameters and Loader Dependency Tracking

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting validateSearch leaves query parameters completely untyped and unsafe. Reading location.search directly in the loader bypasses TanStack Router's dependency tracking, meaning route data will not properly invalidate or re-fetch when search parameters change during client navigation.
```typescript
import { createFileRoute } from '@tanstack/react-router';

// ANTI-PATTERN: Search params are unvalidated, causing runtime type errors.
// The loader reads untracked parameters, failing to re-trigger on param changes.
export const Route = createFileRoute('/dashboard/analytics')({
  loader: async ({ location }) => {
    // Reading directly from raw query string without schema guarantees
    const query = new URLSearchParams(location.search);
    const page = Number(query.get('page')) || 1;
    const interval = query.get('interval') || '7d';
    
    const res = await fetch(`/api/metrics?page=${page}&interval=${interval}`);
    return res.json();
  },
});
```

#### Production Standard (Correct)
> **Standard**: Validating search parameters with Zod guarantees that unexpected or malformed URLs are normalized before hitting route hooks. Explicitly declaring loaderDeps ensures the loader re-executes deterministically whenever page or interval changes.
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { z } from 'zod';

const analyticsSearchSchema = z.object({
  page: z.number().catch(1),
  interval: z.enum(['24h', '7d', '30d']).catch('7d'),
});

type AnalyticsSearch = z.infer<typeof analyticsSearchSchema>;

export const Route = createFileRoute('/dashboard/analytics')({
  validateSearch: (search: Record<string, unknown>): AnalyticsSearch =>
    analyticsSearchSchema.parse(search),
  loaderDeps: ({ search: { page, interval } }) => ({ page, interval }),
  loader: async ({ deps }) => {
    const res = await fetch(`/api/metrics?page=${deps.page}&interval=${deps.interval}`);
    return res.json();
  },
});
```

### Non-Blocking SSR Streaming with defer() and Await

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Awaiting heavy computations or secondary data in the top-level loader blocks the entire HTML stream during SSR. The user receives a blank screen until the slowest service completes, causing poor Core Web Vitals (TTFB and LCP).
```typescript
import { createFileRoute } from '@tanstack/react-router';

export const Route = createFileRoute('/reports/$id')({
  loader: async ({ params: { id } }) => {
    // ANTI-PATTERN: Awaiting slow, secondary operations severely degrades SSR TTFB
    const reportMetadata = await fetch(`/api/reports/${id}/meta`).then(r => r.json());
    const heavyAggregation = await fetch(`/api/reports/${id}/analytics`).then(r => r.json()); // Takes 3000ms+

    return {
      reportMetadata,
      heavyAggregation,
    };
  },
});
```

#### Production Standard (Correct)
> **Standard**: Critical metadata is awaited so the shell and critical content render instantly in the initial SSR stream. The deferred heavy promise streams asynchronously to the client and renders inside a Suspense boundary with Await, optimizing TTFB and perceived performance.
```typescript
import { createFileRoute, defer, Await } from '@tanstack/react-router';
import { Suspense } from 'react';

export const Route = createFileRoute('/reports/$id')({
  loader: async ({ params: { id } }) => {
    // Fast, critical path data is awaited immediately for SSR
    const reportMetadata = await fetch(`/api/reports/${id}/meta`).then(r => r.json());
    // Slow, secondary path is deferred and streamed
    const heavyAggregationPromise = fetch(`/api/reports/${id}/analytics`).then(r => r.json());

    return {
      reportMetadata,
      deferredAnalytics: defer(heavyAggregationPromise),
    };
  },
  component: ReportComponent,
});

function ReportComponent() {
  const { reportMetadata, deferredAnalytics } = Route.useLoaderData();

  return (
    <div>
      <h1>{reportMetadata.title}</h1>
      <Suspense fallback={<div>Loading detailed analytics...</div>}>
        <Await promise={deferredAnalytics}>
          {(data) => <pre>{JSON.stringify(data, null, 2)}</pre>}
        </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 SSR Invariants: Type-Safe Search Validation, Streaming Deferrals, and Loader Dependency Tracking

TanStack Start SSR Invariants: Type-Safe Search Validation, Streaming Deferrals, and Loader Dependency Tracking defines an industrial-grade behavioral standard for frontend engineering. Enforce strict schema validation on URL search parameters via validateSearch, prevent server-side TTFB bottlenecks by mandating defer() streaming for non-critical data, and guarantee deterministic hydration through explicit loaderDeps tracking across TanStack Start routes. 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 TTFB via Monolithic Loaders and Runtime Deserialization Failures via Unvalidated Search Params 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 TTFB via Monolithic Loaders and Runtime Deserialization Failures via Unvalidated Search ParamsCritical
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 route search parameters using standard schema parsers (e.g., Zod, Valibot) within the validateSearch route definition property to guarantee runtime safety and bidirectional type generation.

Engineers MUST ALWAYS validate route search parameters using standard schema parsers (e.g., Zod, Valibot) within the validateSearch route definition property to guarantee runtime safety and bidirectional type generation.

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 block SSR Time-to-First-Byte (TTFB) by awaiting slow, non-critical asynchronous data in loaders

Engineers MUST NOT block SSR Time-to-First-Byte (TTFB) by awaiting slow, non-critical asynchronous data in loaders; secondary promises MUST be wrapped in defer() and rendered client-side using TanStack Router's <Await> and React <Suspense>.

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 ALWAYS declare loader dependencies explicitly in loaderDeps when loader execution depends on validated search parameters

Engineers MUST ALWAYS declare loader dependencies explicitly in loaderDeps when loader execution depends on validated search parameters; loaders MUST NOT read raw URL or untracked state 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.
4

Services exposing fullstack operations MUST encapsulate Node/server-only operations in createServerFn and avoid importing server-only modules into client-consumed route files.

Services exposing fullstack operations MUST encapsulate Node/server-only operations in createServerFn and avoid importing server-only modules into client-consumed route files.

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 read window.location or query parameters imperatively in components or effects

Components NEVER read window.location or query parameters imperatively in components or effects; components MUST consume search parameters exclusively via useSearch() or 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 SSR Invariants: Type-Safe Search Validation, Streaming Deferrals, and Loader Dependency Tracking critical for AI coding assistants?

Enforce strict schema validation on URL search parameters via validateSearch, prevent server-side TTFB bottlenecks by mandating defer() streaming for non-critical data, and guarantee deterministic hydration through explicit loaderDeps tracking across TanStack Start routes. 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 TTFB via Monolithic Loaders and Runtime Deserialization Failures via Unvalidated Search Params) 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