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

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

Enforces strict type safety for TanStack Router search parameters via schema validators, mandates selective SSR streaming via defer() for slow promises to optimize TTFB, and requires server functions (createServerFn) to isolate backend execution and prevent client bundle pollution.

Prohibited Anti-Pattern: Blocking SSR with un-deferred loader waterfalls and unvalidated search parameters causing hydration mismatches

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Start SSR Loaders, Type-Safe Search Params & Deferred Streaming Invariants - Enforces strict type safety for TanStack Router search parameters via schema validators, mandates selective SSR streaming via defer() for slow promises to optimize TTFB, and requires server functions (createServerFn) to isolate backend execution and prevent client bundle pollution.
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-router-ssr-loader-stream-standard"
---

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

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blocking SSR with un-deferred loader waterfalls and unvalidated search parameters causing hydration mismatches

## System Constraints
You are a Principal Fullstack Engineer enforcing TanStack Start and TanStack Router architectural invariants. You must mandate type-safe search parameters using schema validators, isolate server data-fetching via `createServerFn`, and optimize SSR streaming by deferring slow, non-critical promises with `defer()` and `<Await>`.

## Strict Guidelines
- Engineers MUST ALWAYS validate route search parameters using `validateSearch` with a schema validator (Zod, Valibot, or ArkType) to ensure compile-time and runtime type safety.
- Engineers MUST NOT directly `await` slow or non-critical secondary data promises inside the route `loader`; they MUST wrap secondary promises in `defer()` to prevent blocking Time to First Byte (TTFB) during SSR.
- Services MUST be accessed through `createServerFn` with explicit validator schemas and middleware rather than calling database clients directly inside loader closures.
- Components NEVER read search parameters directly via `window.location.search` or `URLSearchParams`; they MUST consume them through `Route.useSearch()` or `useSearch({ from: routeId })`.
- Code SHOULD pair every deferred loader promise with an explicit `<Suspense>` boundary and `<Await>` component to handle streamed states without UI layout thrashing.

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

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly querying the database inside the route loader leaks server-only code into the client bundle, the search params lack schema validation leading to runtime bugs, and directly awaiting the slow analytics query completely blocks SSR streaming, resulting in severe TTFB degradation.
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { db } from '~/server/db'; // Leaking server dependency into client route file

export const Route = createFileRoute('/products')({
  // BAD: Untyped, unvalidated search parameters
  validateSearch: (search: Record<string, unknown>) => search,
  loader: async ({ search }: { search: any }) => {
    // BAD: Server code directly executed in loader without createServerFn
    const criticalProducts = await db.products.findMany({
      where: { category: search.category },
    });
    // BAD: Awaiting slow analytics blocks SSR TTFB for the entire document
    const slowAnalytics = await db.analytics.getTrendsForCategory(search.category);

    return {
      criticalProducts,
      slowAnalytics,
    };
  },
  component: ProductsComponent,
});

function ProductsComponent() {
  // BAD: Untyped search access bypasses TanStack type guarantees
  const { category } = Route.useSearch() as any;
  const { criticalProducts, slowAnalytics } = Route.useLoaderData();
  return <div>{criticalProducts.length} items; Trends: {slowAnalytics.views}</div>;
}
```

#### Production Standard (Correct)
> **Standard**: Search parameters are strictly validated using Zod, ensuring accurate URL state and automatic inference. Database interactions are encapsulated within `createServerFn` to protect server dependencies. Critical product data is resolved immediately for fast initial HTML rendering, while slow analytics are wrapped with `defer()` and resolved asynchronously via `<Await>` and `<Suspense>` streaming.
```typescript
import { createFileRoute, defer, Await } from '@tanstack/react-router';
import { createServerFn } from '@tanstack/start';
import { Suspense } from 'react';
import { z } from 'zod';

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

const getProductsFn = createServerFn({ method: 'GET' })
  .validator((d: { category: string; page: number }) => d)
  .handler(async ({ data }) => {
    const { db } = await import('~/server/db');
    return db.products.findMany({ where: { category: data.category } });
  });

const getSlowAnalyticsFn = createServerFn({ method: 'GET' })
  .validator((category: string) => category)
  .handler(async ({ data: category }) => {
    const { db } = await import('~/server/db');
    return db.analytics.getTrendsForCategory(category);
  });

export const Route = createFileRoute('/products')({
  validateSearch: zodSearchValidator(productSearchSchema),
  loader: async ({ search }) => {
    // GOOD: Await critical data required for initial meaningful paint
    const criticalProducts = await getProductsFn({ data: search });
    // GOOD: Defer non-critical promise to stream it over the existing SSR stream
    const deferredAnalytics = getSlowAnalyticsFn({ data: search.category });

    return {
      criticalProducts,
      deferredAnalytics: defer(deferredAnalytics),
    };
  },
  component: ProductsComponent,
});

function ProductsComponent() {
  const { criticalProducts, deferredAnalytics } = Route.useLoaderData();

  return (
    <div>
      <ProductList items={criticalProducts} />
      <Suspense fallback={<AnalyticsSkeleton />}>
        <Await promise={deferredAnalytics}>
          {(analytics) => <AnalyticsCard data={analytics} />}
        </Await>
      </Suspense>
    </div>
  );
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: TanStack Start SSR Loaders, Type-Safe Search Params & Deferred Streaming Invariants

TanStack Start SSR Loaders, Type-Safe Search Params & Deferred Streaming Invariants defines an industrial-grade behavioral standard for frontend engineering. Enforces strict type safety for TanStack Router search parameters via schema validators, mandates selective SSR streaming via defer() for slow promises to optimize TTFB, and requires server functions (createServerFn) to isolate backend execution and prevent client bundle pollution. 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 un-deferred loader waterfalls and unvalidated search parameters causing hydration mismatches 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 un-deferred loader waterfalls and unvalidated search parameters causing hydration mismatchesCritical
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 schema validator (Zod, Valibot, or ArkType) to ensure compile-time and runtime type safety.

Engineers MUST ALWAYS validate route search parameters using `validateSearch` with a schema validator (Zod, Valibot, or ArkType) to ensure 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.
2

Engineers MUST NOT directly `await` slow or non-critical secondary data promises inside the route `loader`

Engineers MUST NOT directly `await` slow or non-critical secondary data promises inside the route `loader`; they MUST wrap secondary promises in `defer()` to prevent blocking Time to First Byte (TTFB) during SSR.

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

Services MUST be accessed through `createServerFn` with explicit validator schemas and middleware rather than calling database clients directly inside loader closures.

Services MUST be accessed through `createServerFn` with explicit validator schemas and middleware rather than calling database clients directly inside loader closures.

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 NEVER read search parameters directly via `window.location.search` or `URLSearchParams`

Components NEVER read search parameters directly via `window.location.search` or `URLSearchParams`; they MUST consume them through `Route.useSearch()` or `useSearch({ from: routeId })`.

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

Code SHOULD pair every deferred loader promise with an explicit `<Suspense>` boundary and `<Await>` component to handle streamed states without UI layout thrashing.

Code SHOULD pair every deferred loader promise with an explicit `<Suspense>` boundary and `<Await>` component to handle streamed states without UI layout thrashing.

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 & Deferred Streaming Invariants critical for AI coding assistants?

Enforces strict type safety for TanStack Router search parameters via schema validators, mandates selective SSR streaming via defer() for slow promises to optimize TTFB, and requires server functions (createServerFn) to isolate backend execution and prevent client bundle pollution. 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 un-deferred loader waterfalls and unvalidated search parameters causing hydration mismatches) 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