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

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

Mandates strict schema validation via validateSearch, intentional separation of critical vs deferred SSR data via defer(), and explicit loaderDeps mapping. Prevents severe TTFB latency degradation, client-server hydration mismatch, and unsynchronized route transitions.

Prohibited Anti-Pattern: Degrading SSR TTFB with monolithic non-deferred loaders and fetching search-dependent data via client useEffect hooks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Start SSR Loaders, Streaming Invariants, and Type-Safe Search Params - Mandates strict schema validation via validateSearch, intentional separation of critical vs deferred SSR data via defer(), and explicit loaderDeps mapping. Prevents severe TTFB latency degradation, client-server hydration mismatch, and unsynchronized route transitions.
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-loader-streaming-standard"
---

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

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Degrading SSR TTFB with monolithic non-deferred loaders and fetching search-dependent data via client useEffect hooks

## System Constraints
You are a Principal Software Architect enforcing TanStack Start and TanStack Router SSR architectural invariants. Mandate type-safe search param validation via zod/standard-schema, explicit loader dependencies with loaderDeps, deterministic defer() streaming for slow requests to optimize TTFB, and server function execution isolation.

## Strict Guidelines
- Engineers MUST ALWAYS validate route search parameters using validateSearch with a validated schema (e.g., Zod, Valibot) returning deterministic fallback defaults.
- Engineers MUST ALWAYS declare loaderDeps: ({ search }) => ({ ... }) when a loader depends on search parameters; loaders MUST NEVER read search directly from global state or context.
- Engineers MUST wrap non-critical, slow promises with defer() from @tanstack/react-router inside SSR loaders to stream content without delaying initial HTML response (TTFB).
- Components MUST consume deferred promises using the <Await> component wrapped in a React <Suspense> boundary with a valid fallback UI.
- Components NEVER trigger secondary fetches inside client-side useEffect hooks for search-dependent UI; all query mutations MUST flow through navigate({ search: (prev) => ... }).
- Services MUST execute server-only operations inside createServerFn() and NEVER leak node-exclusive or database modules into client-visible isomorphic route bundles.

## Bad vs Good Implementations
### Type-Safe Search Params with Deferred Data Streaming in SSR Loader

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Blocks initial document SSR response until the slowest service responds (ruining TTFB), accesses search parameters in an untyped manner from location without validation, and bypasses router lifecycle by triggering unmanaged client-side fetches inside useEffect.
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { useEffect, useState } from 'react';

// ANTI-PATTERN: Unvalidated search params, blocking waterfall loader, and client useEffect sync
export const Route = createFileRoute('/products')({
  loader: async ({ location }) => {
    // Blocking entire SSR response on both fast critical and slow analytics queries
    const criticalProduct = await fetch(`/api/products/${location.search.id}`).then(r => r.json());
    const slowAnalytics = await fetch(`/api/analytics/${location.search.id}`).then(r => r.json());
    return { criticalProduct, slowAnalytics };
  },
  component: ProductPage,
});

function ProductPage() {
  const { criticalProduct, slowAnalytics } = Route.useLoaderData();
  const [filter, setFilter] = useState('');

  useEffect(() => {
    // Desynchronized URL and client-state refetch
    fetch(`/api/reviews?filter=${filter}`);
  }, [filter]);

  return <div>{criticalProduct.name} - {slowAnalytics.views}</div>;
}
```

#### Production Standard (Correct)
> **Standard**: Validates search parameters using Zod, declares reactive dependencies via loaderDeps, awaits critical product data for instant TTFB/SEO, defers slow telemetry using defer(), and renders the deferred stream via <Await> and <Suspense>.
```typescript
import { createFileRoute, defer, Await } from '@tanstack/react-router';
import { Suspense } from 'react';
import { z } from 'zod';
import { createServerFn } from '@tanstack/start';

const productSearchSchema = z.object({
  productId: z.string().min(1),
  filter: z.string().default('all'),
});

const getCriticalProduct = createServerFn({ method: 'GET' })
  .validator((d: string) => d)
  .handler(async ({ data: id }) => {
    return { id, name: 'Enterprise Gateway' };
  });

const getSlowAnalytics = createServerFn({ method: 'GET' })
  .validator((d: string) => d)
  .handler(async ({ data: id }) => {
    await new Promise((res) => setTimeout(res, 1200));
    return { views: 42000, conversionRate: '3.4%' };
  });

export const Route = createFileRoute('/products')({
  validateSearch: (search) => productSearchSchema.parse(search),
  loaderDeps: ({ search: { productId } }) => ({ productId }),
  loader: async ({ deps: { productId } }) => {
    const criticalProduct = await getCriticalProduct({ data: productId });
    const slowAnalyticsPromise = getSlowAnalytics({ data: productId });

    return {
      criticalProduct,
      deferredAnalytics: defer(slowAnalyticsPromise),
    };
  },
  component: ProductPage,
});

function ProductPage() {
  const { criticalProduct, deferredAnalytics } = Route.useLoaderData();

  return (
    <main>
      <h1>{criticalProduct.name}</h1>
      <Suspense fallback={<div>Loading telemetry...</div>}>
        <Await promise={deferredAnalytics}>
          {(analytics) => (
            <div>Views: {analytics.views} ({analytics.conversionRate})</div>
          )}
        </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, Streaming Invariants, and Type-Safe Search Params

TanStack Start SSR Loaders, Streaming Invariants, and Type-Safe Search Params defines an industrial-grade behavioral standard for frontend engineering. Mandates strict schema validation via validateSearch, intentional separation of critical vs deferred SSR data via defer(), and explicit loaderDeps mapping. Prevents severe TTFB latency degradation, client-server hydration mismatch, and unsynchronized route transitions. 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: Degrading SSR TTFB with monolithic non-deferred loaders and fetching search-dependent data via client useEffect hooks 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 DriftDegrading SSR TTFB with monolithic non-deferred loaders and fetching search-dependent data via client useEffect hooksCritical
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 validated schema (e.g., Zod, Valibot) returning deterministic fallback defaults.

Engineers MUST ALWAYS validate route search parameters using validateSearch with a validated schema (e.g., Zod, Valibot) returning deterministic fallback defaults.

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 }) => ({ ... }) when a loader depends on search parameters; loaders MUST NEVER read search directly from global state or context.

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 wrap non-critical, slow promises with defer() from @tanstack/react-router inside SSR loaders to stream content without delaying initial HTML response (TTFB).

Engineers MUST wrap non-critical, slow promises with defer() from @tanstack/react-router inside SSR loaders to stream content without delaying initial HTML response (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.
4

Components MUST consume deferred promises using the <Await> component wrapped in a React <Suspense> boundary with a valid fallback UI.

Components MUST consume deferred promises using the <Await> component wrapped in a React <Suspense> boundary with a valid fallback UI.

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 trigger secondary fetches inside client-side useEffect hooks for search-dependent UI

Components NEVER trigger secondary fetches inside client-side useEffect hooks for search-dependent UI; all query mutations MUST flow through navigate({ search: (prev) => ... }).

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 execute server-only operations inside createServerFn() and NEVER leak node-exclusive or database modules into client-visible isomorphic route bundles.

Services MUST execute server-only operations inside createServerFn() and NEVER leak node-exclusive or database modules into client-visible isomorphic route bundles.

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

Mandates strict schema validation via validateSearch, intentional separation of critical vs deferred SSR data via defer(), and explicit loaderDeps mapping. Prevents severe TTFB latency degradation, client-server hydration mismatch, and unsynchronized route transitions. 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 (Degrading SSR TTFB with monolithic non-deferred loaders and fetching search-dependent data via client useEffect hooks) 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