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

TanStack Start SSR: Type-Safe Search Validation, Granular Loader Dependencies, and Deferred Data Streaming

Enforces strict type safety for URL search parameters via schema validators, prevents SSR render blocking through deferred streaming promises, and ensures loaders trigger re-executions only when declared dependencies mutate. Failing to adhere leads to TTFB degradation, hydration mismatch exceptions, and silent cache invalidation bugs in fullstack TanStack applications.

Prohibited Anti-Pattern: Blocking SSR on non-critical queries and relying on untyped search params without loaderDeps

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Start SSR: Type-Safe Search Validation, Granular Loader Dependencies, and Deferred Data Streaming - Enforces strict type safety for URL search parameters via schema validators, prevents SSR render blocking through deferred streaming promises, and ensures loaders trigger re-executions only when declared dependencies mutate. Failing to adhere leads to TTFB degradation, hydration mismatch exceptions, and silent cache invalidation bugs in fullstack TanStack applications.
globs: app/routes/**/*.{ts,tsx}, src/routes/**/*.{ts,tsx}, app/**/*.{ts,tsx}, src/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/tanstack-start-router-ssr-production-standard"
---

# TanStack Start SSR: Type-Safe Search Validation, Granular Loader Dependencies, and Deferred Data Streaming

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blocking SSR on non-critical queries and relying on untyped search params without loaderDeps

## System Constraints
You are a Principal Software Architect enforcing production standards for TanStack Start and TanStack Router SSR. You mandate schema-validated search parameters via validateSearch, deferred promises (defer()) wrapped in Suspense and Await for non-critical assets to preserve streaming TTFB, and explicit loaderDeps declarations to prevent stale data or catastrophic infinite loader loops.

## Strict Guidelines
- Engineers MUST ALWAYS validate search parameters using a strict parser/schema (such as Zod, Valibot, or ArkType) via the `validateSearch` route option.
- Engineers MUST NEVER access raw search parameters or invoke `useSearch` without declaring `validateSearch` on the associated route definition.
- Loaders MUST declare explicit dependencies using `loaderDeps: ({ search }) => ({ ... })` whenever loader execution depends on URL search parameters.
- Engineers MUST use `defer()` for non-critical, slow-resolving secondary data inside loaders to enable progressive SSR streaming and maintain fast Time to First Byte (TTFB).
- Components consuming deferred loader data MUST ALWAYS wrap consumers in `<Suspense>` and use the `<Await>` component with proper fallback boundaries.
- Engineers MUST NOT invoke client-only APIs (such as `window`, `localStorage`, or `document`) during the initial phase of `loader` execution or server route rendering without proper hydration guards.
- Data fetching logic inside TanStack Start loaders MUST utilize type-safe server functions created via `createServerFn` to preserve end-to-end type safety and boundary isolation.

## Bad vs Good Implementations
### Type-Safe Search Parameters and Granular Loader Dependencies

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting `validateSearch` introduces runtime injection and parse errors. Without `loaderDeps`, TanStack Router does not observe URL search changes by default, leaving the loader stale when query parameters change.
```typescript
import { createFileRoute } from '@tanstack/react-router';

// ANTI-PATTERN: Missing validateSearch, missing loaderDeps, accessing raw search
export const Route = createFileRoute('/products')({
  loader: async ({ location }) => {
    // Bypassing type safety; loader will not re-run when search params change
    const page = Number((location.search as any).page || 1);
    const filter = (location.search as any).filter || '';
    return fetchProducts({ page, filter });
  },
  component: ProductsComponent,
});
```

#### Production Standard (Correct)
> **Standard**: Search parameters are sanitized and typed via Zod in `validateSearch`. Declaring `loaderDeps` guarantees TanStack Router re-invokes the loader whenever `page` or `filter` changes.
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { z } from 'zod';
import { fetchProducts } from '~/server/products';

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

export const Route = createFileRoute('/products')({
  validateSearch: (search) => productSearchSchema.parse(search),
  loaderDeps: ({ search: { page, filter } }) => ({ page, filter }),
  loader: async ({ deps }) => {
    return fetchProducts({ page: deps.page, filter: deps.filter });
  },
  component: ProductsComponent,
});
```

### Deferred Streaming with defer() and <Await>

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Awaiting slow database or third-party queries directly in the loader blocks the HTTP response header delivery and full SSR stream, severely degrading Core Web Vitals (TTFB/FCP).
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { fetchCriticalProfile, fetchSlowAnalytics } from '~/server/dashboard';

// ANTI-PATTERN: Awaiting slow non-critical data blocks SSR stream and TTFB
export const Route = createFileRoute('/dashboard')({
  loader: async () => {
    const criticalProfile = await fetchCriticalProfile();
    // Halts SSR rendering until slow analytics query finishes
    const slowAnalytics = await fetchSlowAnalytics();
    return { criticalProfile, slowAnalytics };
  },
  component: DashboardComponent,
});
```

#### Production Standard (Correct)
> **Standard**: Awaiting critical data delivers initial HTML immediately. Deferring the slow analytics promise allows the server to stream the remainder over the wire into `<Suspense>` via `<Await>` without blocking initial page paint.
```typescript
import { createFileRoute, defer, Await } from '@tanstack/react-router';
import { Suspense } from 'react';
import { fetchCriticalProfile, fetchSlowAnalytics } from '~/server/dashboard';

export const Route = createFileRoute('/dashboard')({
  loader: async () => {
    const criticalProfile = await fetchCriticalProfile();
    // Fast data is awaited; slow non-critical data is wrapped in defer()
    const deferredAnalytics = defer(fetchSlowAnalytics());
    return { criticalProfile, deferredAnalytics };
  },
  component: DashboardComponent,
});

function DashboardComponent() {
  const { criticalProfile, deferredAnalytics } = Route.useLoaderData();
  return (
    <div>
      <h1>Welcome, {criticalProfile.name}</h1>
      <Suspense fallback={<div>Loading analytics stream...</div>}>
        <Await promise={deferredAnalytics}>
          {(data) => <AnalyticsChart data={data} />}
        </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: Type-Safe Search Validation, Granular Loader Dependencies, and Deferred Data Streaming

TanStack Start SSR: Type-Safe Search Validation, Granular Loader Dependencies, and Deferred Data Streaming defines an industrial-grade behavioral standard for frontend engineering. Enforces strict type safety for URL search parameters via schema validators, prevents SSR render blocking through deferred streaming promises, and ensures loaders trigger re-executions only when declared dependencies mutate. Failing to adhere leads to TTFB degradation, hydration mismatch exceptions, and silent cache invalidation bugs in fullstack TanStack applications. 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 on non-critical queries and relying on untyped search params without 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 on non-critical queries and relying on untyped search params without 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 parameters using a strict parser/schema (such as Zod, Valibot, or ArkType) via the `validateSearch` route option.

Engineers MUST ALWAYS validate search parameters using a strict parser/schema (such as Zod, Valibot, or ArkType) via the `validateSearch` route option.

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 NEVER access raw search parameters or invoke `useSearch` without declaring `validateSearch` on the associated route definition.

Engineers MUST NEVER access raw search parameters or invoke `useSearch` without declaring `validateSearch` on the associated route definition.

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

Loaders MUST declare explicit dependencies using `loaderDeps

Loaders MUST declare explicit dependencies using `loaderDeps: ({ search }) => ({ ... })` whenever loader execution depends on URL search parameters.

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 use `defer()` for non-critical, slow-resolving secondary data inside loaders to enable progressive SSR streaming and maintain fast Time to First Byte (TTFB).

Engineers MUST use `defer()` for non-critical, slow-resolving secondary data inside loaders to enable progressive SSR streaming and maintain fast Time to First Byte (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

Components consuming deferred loader data MUST ALWAYS wrap consumers in `<Suspense>` and use the `<Await>` component with proper fallback boundaries.

Components consuming deferred loader data MUST ALWAYS wrap consumers in `<Suspense>` and use the `<Await>` component with proper fallback 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

Engineers MUST NOT invoke client-only APIs (such as `window`, `localStorage`, or `document`) during the initial phase of `loader` execution or server route rendering without proper hydration guards.

Engineers MUST NOT invoke client-only APIs (such as `window`, `localStorage`, or `document`) during the initial phase of `loader` execution or server route rendering without proper hydration guards.

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.
7

Data fetching logic inside TanStack Start loaders MUST utilize type-safe server functions created via `createServerFn` to preserve end-to-end type safety and boundary isolation.

Data fetching logic inside TanStack Start loaders MUST utilize type-safe server functions created via `createServerFn` to preserve end-to-end type safety and boundary isolation.

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: Type-Safe Search Validation, Granular Loader Dependencies, and Deferred Data Streaming critical for AI coding assistants?

Enforces strict type safety for URL search parameters via schema validators, prevents SSR render blocking through deferred streaming promises, and ensures loaders trigger re-executions only when declared dependencies mutate. Failing to adhere leads to TTFB degradation, hydration mismatch exceptions, and silent cache invalidation bugs in fullstack TanStack applications. 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 on non-critical queries and relying on untyped search params without 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