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

TanStack Start SSR Loaders, Type-Safe Search Params, and Deferred Streaming Standard

Enforces strict type safety for URL search params, prevents SSR-blocking data waterfalls through deferred promise streaming, and eliminates client-server hydration mismatches in TanStack Start. Prohibits direct access to window.location or unvalidated search params during server-side renders and requires non-critical async loader data to be deferred via defer() and consumed with Suspense and Await.

Prohibited Anti-Pattern: Blocking Critical SSR with Un-deferred Async Loaders and Unvalidated Raw Search Parameter Access

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Start SSR Loaders, Type-Safe Search Params, and Deferred Streaming Standard - Enforces strict type safety for URL search params, prevents SSR-blocking data waterfalls through deferred promise streaming, and eliminates client-server hydration mismatches in TanStack Start. Prohibits direct access to window.location or unvalidated search params during server-side renders and requires non-critical async loader data to be deferred via defer() and consumed with Suspense and Await.
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-type-safe-ssr-streaming-production-standard"
---

# TanStack Start SSR Loaders, Type-Safe Search Params, and Deferred Streaming Standard

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blocking Critical SSR with Un-deferred Async Loaders and Unvalidated Raw Search Parameter Access

## System Constraints
You are a Principal Software Architect enforcing zero-defect TanStack Start and TanStack Router fullstack architecture. Enforce strict type-safe search param validation via Zod or Standard Schema, unblock the critical SSR render path using defer() for secondary queries, and strictly reject any unvalidated query parameter access, manual location parsing, or unhandled loader hydration waterfalls.

## Strict Guidelines
- Engineers MUST ALWAYS validate route search parameters using `validateSearch` with a Zod schema or Standard Schema validator on the route definition.
- Engineers MUST ALWAYS access route search parameters via `Route.useSearch()` or `useSearch({ from: Route.fullPath })` to guarantee compile-time and runtime type safety.
- Engineers MUST NOT access `window.location.search`, `new URLSearchParams()`, or raw location objects directly inside route components or SSR loader contexts.
- Engineers MUST separate critical SSR data from secondary data in loaders, wrapping non-critical promises with `defer()` from `@tanstack/react-router` to stream HTML without blocking TTFB.
- Components MUST ALWAYS wrap deferred loader promises in `<Suspense>` and `<Await>` blocks with explicit fallback boundaries.
- Loaders MUST NOT execute sequential waterfalls for independent asynchronous requests; use `Promise.all` for critical data and separate deferred promises for background streams.
- Server functions invoked inside loaders MUST be defined with `createServerFn` from `@tanstack/start` with explicit input validation via `.validator()`.
- Components NEVER use `useEffect` or client-side lifecycle hooks to fetch initial route data that belongs in the route `loader`.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Fails to define `validateSearch`, leading to untyped and unvalidated query parameters. Awaits slow analytics queries directly in the loader, causing severe TTFB degradation during SSR instead of streaming the initial HTML shell.
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { useEffect, useState } from 'react';

export const Route = createFileRoute('/dashboard')({
  // BAD: No search parameter schema validation
  loader: async ({ location }) => {
    // BAD: Parsing raw search manually, bypassing router type safety
    const params = new URLSearchParams(location.search);
    const page = Number(params.get('page') || 1);

    // BAD: Blocking SSR critical path by awaiting slow auxiliary metrics
    const criticalUser = await fetch(`https://api.internal/user`).then((r) => r.json());
    const slowAnalytics = await fetch(`https://api.internal/metrics?page=${page}`).then((r) => r.json());

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

function DashboardComponent() {
  const { criticalUser, slowAnalytics } = Route.useLoaderData();
  // BAD: Missing Suspense/Await for potentially slow, streamed data
  return (
    <div>
      <h1>Welcome {criticalUser.name}</h1>
      <div>Analytics: {JSON.stringify(slowAnalytics)}</div>
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates search parameters using Zod and maps dependencies with `loaderDeps`. The loader awaits fast, critical user data for immediate SSR HTML while deferring slow metrics using `defer()`, rendered client-side via `<Suspense>` and `<Await>`.
```typescript
import { createFileRoute, defer, Await } from '@tanstack/react-router';
import { Suspense } from 'react';
import { z } from 'zod';

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

export const Route = createFileRoute('/dashboard')({
  validateSearch: (search) => dashboardSearchSchema.parse(search),
  loaderDeps: ({ search: { page, filter } }) => ({ page, filter }),
  loader: async ({ deps }) => {
    // GOOD: Critical shell data is awaited to satisfy SSR requirements
    const criticalUserPromise = fetch('https://api.internal/user').then((r) => r.json());
    
    // GOOD: Secondary slow data is not awaited; deferred for HTTP streaming
    const slowAnalyticsPromise = fetch(`https://api.internal/metrics?page=${deps.page}`).then((r) => r.json());

    const criticalUser = await criticalUserPromise;

    return {
      criticalUser,
      deferredAnalytics: defer(slowAnalyticsPromise),
    };
  },
  component: DashboardComponent,
});

function DashboardComponent() {
  const { criticalUser, deferredAnalytics } = Route.useLoaderData();
  const { page } = Route.useSearch();

  return (
    <main>
      <h1>Welcome, {criticalUser.name} (Page {page})</h1>
      <Suspense fallback={<p>Streaming telemetry data...</p>}>
        <Await promise={deferredAnalytics}>
          {(analytics) => <pre>{JSON.stringify(analytics, null, 2)}</pre>}
        </Await>
      </Suspense>
    </main>
  );
}
```

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 Loaders, Type-Safe Search Params, and Deferred Streaming Standard

TanStack Start SSR Loaders, Type-Safe Search Params, and Deferred Streaming Standard defines an industrial-grade behavioral standard for frontend engineering. Enforces strict type safety for URL search params, prevents SSR-blocking data waterfalls through deferred promise streaming, and eliminates client-server hydration mismatches in TanStack Start. Prohibits direct access to window.location or unvalidated search params during server-side renders and requires non-critical async loader data to be deferred via defer() and consumed with Suspense and Await. 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 Critical SSR with Un-deferred Async Loaders and Unvalidated Raw Search Parameter Access 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 Critical SSR with Un-deferred Async Loaders and Unvalidated Raw Search Parameter AccessCritical
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 `validateSearch` with a Zod schema or Standard Schema validator on the route definition.

Engineers MUST ALWAYS validate route search parameters using `validateSearch` with a Zod schema or Standard Schema validator on the 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.
2

Engineers MUST ALWAYS access route search parameters via `Route.useSearch()` or `useSearch({ from

Engineers MUST ALWAYS access route search parameters via `Route.useSearch()` or `useSearch({ from: Route.fullPath })` to guarantee compile-time and runtime type safety.

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 NOT access `window.location.search`, `new URLSearchParams()`, or raw location objects directly inside route components or SSR loader contexts.

Engineers MUST NOT access `window.location.search`, `new URLSearchParams()`, or raw location objects directly inside route components or SSR loader contexts.

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 separate critical SSR data from secondary data in loaders, wrapping non-critical promises with `defer()` from `@tanstack/react-router` to stream HTML without blocking TTFB.

Engineers MUST separate critical SSR data from secondary data in loaders, wrapping non-critical promises with `defer()` from `@tanstack/react-router` to stream HTML without blocking 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 MUST ALWAYS wrap deferred loader promises in `<Suspense>` and `<Await>` blocks with explicit fallback boundaries.

Components MUST ALWAYS wrap deferred loader promises in `<Suspense>` and `<Await>` blocks with explicit 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

Loaders MUST NOT execute sequential waterfalls for independent asynchronous requests

Loaders MUST NOT execute sequential waterfalls for independent asynchronous requests; use `Promise.all` for critical data and separate deferred promises for background streams.

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

Server functions invoked inside loaders MUST be defined with `createServerFn` from `@tanstack/start` with explicit input validation via `.validator()`.

Server functions invoked inside loaders MUST be defined with `createServerFn` from `@tanstack/start` with explicit input validation via `.validator()`.

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

Components NEVER use `useEffect` or client-side lifecycle hooks to fetch initial route data that belongs in the route `loader`.

Components NEVER use `useEffect` or client-side lifecycle hooks to fetch initial route data that belongs in the route `loader`.

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 Loaders, Type-Safe Search Params, and Deferred Streaming Standard critical for AI coding assistants?

Enforces strict type safety for URL search params, prevents SSR-blocking data waterfalls through deferred promise streaming, and eliminates client-server hydration mismatches in TanStack Start. Prohibits direct access to window.location or unvalidated search params during server-side renders and requires non-critical async loader data to be deferred via defer() and consumed with Suspense and Await. 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 Critical SSR with Un-deferred Async Loaders and Unvalidated Raw Search Parameter Access) 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