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

TanStack Start Invariants: Type-Safe Search Params, Server Functions, and Deferred Streaming

Mandates strict schema-validated search parameters, isolated server functions via createServerFn, and explicit stream deferral via defer() and Await for non-critical loader promises in TanStack Start SSR. Violating these patterns degrades Time to First Byte (TTFB), causes hydration mismatches, and risks leaking server secrets to the client bundle.

Prohibited Anti-Pattern: Blocking TTFB via Monolithic Loaders and Bypassing Search Param Schema Validation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: TanStack Start Invariants: Type-Safe Search Params, Server Functions, and Deferred Streaming - Mandates strict schema-validated search parameters, isolated server functions via createServerFn, and explicit stream deferral via defer() and Await for non-critical loader promises in TanStack Start SSR. Violating these patterns degrades Time to First Byte (TTFB), causes hydration mismatches, and risks leaking server secrets to the client bundle.
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-search-params-standard"
---

# TanStack Start Invariants: Type-Safe Search Params, Server Functions, and Deferred Streaming

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Blocking TTFB via Monolithic Loaders and Bypassing Search Param Schema Validation

## System Constraints
You are a Principal Software Architect enforcing production invariants for TanStack Start and TanStack Router fullstack SSR. You enforce zero-compromise type safety for search params via schemas, boundary isolation with createServerFn, and non-blocking streaming SSR via defer() and <Await>.

## Strict Guidelines
- Engineers MUST ALWAYS validate route search parameters using `validateSearch` with a runtime schema validator (e.g., Zod, ArkType, or Valibot) on `createFileRoute` definitions.
- Engineers MUST NOT access `window.location.search` or read unvalidated search parameters with `useSearch({ strict: false })` in client components.
- Loaders MUST NOT await slow or secondary I/O operations directly on the critical SSR render path; non-critical promises MUST be wrapped with `defer()` and resolved asynchronously on the client.
- Deferred promises MUST be consumed using `<Suspense>` boundaries coupled with the `<Await promise={...}>` component to prevent streaming deadlocks and layout shift.
- Server-side mutations and direct database queries MUST be encapsulated inside `createServerFn({ method: 'GET' | 'POST' })` to guarantee boundary tree-shaking and prevent server secret leakage.
- Components NEVER execute client-side data fetching hooks (e.g., raw `useEffect`) for data that belongs to the initial route state; all initial route state must be initialized through the route `loader`.
- Loaders returning serializable state MUST ensure all returned properties are JSON-compatible; non-serializable classes or circular references MUST NOT be passed from SSR loaders.

## Bad vs Good Implementations
### Search Parameter Validation & Type-Safe Consumption

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Omitting validateSearch causes runtime fragility, lacks default fallbacks, and strips TypeScript compile-time guarantees from Route.useSearch and navigation links.
```typescript
import { createFileRoute } from '@tanstack/react-router';

// ANTI-PATTERN: No validateSearch defined, consuming unvalidated search state
export const Route = createFileRoute('/dashboard')({
  component: DashboardComponent,
});

function DashboardComponent() {
  // Runtime error-prone and untyped; page and filter can be undefined or malicious injection
  const { page, filter } = Route.useSearch({ strict: false }) as any;
  return (
    <div>
      Page: {page}
      Filter: {filter}
    </div>
  );
}
```

#### Production Standard (Correct)
> **Standard**: Validates incoming query parameters against a Zod schema with resilient defaults, producing strictly typed search params in useSearch and throughout the router tree.
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { z } from 'zod';

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

type SearchParams = z.infer<typeof searchSchema>;

export const Route = createFileRoute('/dashboard')({
  validateSearch: (search: Record<string, unknown>): SearchParams => {
    return searchSchema.parse(search);
  },
  component: DashboardComponent,
});

function DashboardComponent() {
  const { page, filter } = Route.useSearch();
  return (
    <div>
      Page: {page}
      Filter: {filter}
    </div>
  );
}
```

### SSR Server Functions with Deferred Streaming

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Imports server DB directly into route file, and awaits slow metrics directly in loader, freezing HTML response generation and degrading TTFB across the application.
```typescript
import { createFileRoute } from '@tanstack/react-router';
import { db } from '~/server/db'; // DANGER: Leaks server dependencies into client bundle

export const Route = createFileRoute('/analytics')({
  loader: async () => {
    // ANTI-PATTERN: Awaiting a slow query directly blocks the initial TTFB on SSR
    const criticalUser = await db.user.findFirst();
    const slowMetrics = await db.metrics.aggregateHeavy();

    return {
      user: criticalUser,
      metrics: slowMetrics,
    };
  },
  component: AnalyticsComponent,
});
```

#### Production Standard (Correct)
> **Standard**: Uses createServerFn to isolate server logic, awaits only critical path user data for swift TTFB, and wraps slow data in defer() and <Await> with Suspense for non-blocking streaming.
```typescript
import { createFileRoute, defer, Await } from '@tanstack/react-router';
import { createServerFn } from '@tanstack/start';
import { Suspense } from 'react';

const getCriticalUser = createServerFn({ method: 'GET' }).handler(async () => {
  const { db } = await import('~/server/db');
  return db.user.findFirstOrThrow();
});

const getHeavyMetrics = createServerFn({ method: 'GET' }).handler(async () => {
  const { db } = await import('~/server/db');
  return db.metrics.aggregateHeavy();
});

export const Route = createFileRoute('/analytics')({
  loader: async () => {
    const user = await getCriticalUser();
    // Fast-path HTML stream: defer heavy background promise
    const slowMetricsPromise = getHeavyMetrics();

    return {
      user,
      deferredMetrics: defer(slowMetricsPromise),
    };
  },
  component: AnalyticsComponent,
});

function AnalyticsComponent() {
  const { user, deferredMetrics } = Route.useLoaderData();

  return (
    <main>
      <h1>Welcome, {user.name}</h1>
      <Suspense fallback={<div>Loading heavy metrics...</div>}>
        <Await promise={deferredMetrics}>
          {(metrics) => <pre>{JSON.stringify(metrics, 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 Invariants: Type-Safe Search Params, Server Functions, and Deferred Streaming

TanStack Start Invariants: Type-Safe Search Params, Server Functions, and Deferred Streaming defines an industrial-grade behavioral standard for frontend engineering. Mandates strict schema-validated search parameters, isolated server functions via createServerFn, and explicit stream deferral via defer() and Await for non-critical loader promises in TanStack Start SSR. Violating these patterns degrades Time to First Byte (TTFB), causes hydration mismatches, and risks leaking server secrets to the client bundle. 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 TTFB via Monolithic Loaders and Bypassing Search Param Schema Validation 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 TTFB via Monolithic Loaders and Bypassing Search Param Schema ValidationCritical
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 runtime schema validator (e.g., Zod, ArkType, or Valibot) on `createFileRoute` definitions.

Engineers MUST ALWAYS validate route search parameters using `validateSearch` with a runtime schema validator (e.g., Zod, ArkType, or Valibot) on `createFileRoute` definitions.

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 access `window.location.search` or read unvalidated search parameters with `useSearch({ strict

Engineers MUST NOT access `window.location.search` or read unvalidated search parameters with `useSearch({ strict: false })` in client components.

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 NOT await slow or secondary I/O operations directly on the critical SSR render path

Loaders MUST NOT await slow or secondary I/O operations directly on the critical SSR render path; non-critical promises MUST be wrapped with `defer()` and resolved asynchronously on the client.

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

Deferred promises MUST be consumed using `<Suspense>` boundaries coupled with the `<Await promise={...}>` component to prevent streaming deadlocks and layout shift.

Deferred promises MUST be consumed using `<Suspense>` boundaries coupled with the `<Await promise={...}>` component to prevent streaming deadlocks and layout shift.

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

Server-side mutations and direct database queries MUST be encapsulated inside `createServerFn({ method

Server-side mutations and direct database queries MUST be encapsulated inside `createServerFn({ method: 'GET' | 'POST' })` to guarantee boundary tree-shaking and prevent server secret leakage.

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

Components NEVER execute client-side data fetching hooks (e.g., raw `useEffect`) for data that belongs to the initial route state

Components NEVER execute client-side data fetching hooks (e.g., raw `useEffect`) for data that belongs to the initial route state; all initial route state must be initialized through 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.
7

Loaders returning serializable state MUST ensure all returned properties are JSON-compatible

Loaders returning serializable state MUST ensure all returned properties are JSON-compatible; non-serializable classes or circular references MUST NOT be passed from SSR loaders.

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

Mandates strict schema-validated search parameters, isolated server functions via createServerFn, and explicit stream deferral via defer() and Await for non-critical loader promises in TanStack Start SSR. Violating these patterns degrades Time to First Byte (TTFB), causes hydration mismatches, and risks leaking server secrets to the client bundle. 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 TTFB via Monolithic Loaders and Bypassing Search Param Schema Validation) 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