web-routing-tanstack-router

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

TanStack Router Patterns

TanStack Router 模式

Quick Guide: TanStack Router provides fully type-safe client-side routing for React. Use file-based routing with
@tanstack/router-plugin
for automatic route tree generation. Define search params with Zod via
@tanstack/zod-adapter
. Use
loader
for data fetching,
beforeLoad
for guards/redirects, and
createRootRouteWithContext
for dependency injection. Version: v1.x (stable).

<critical_requirements>
快速指南: TanStack Router 为React提供完全类型安全的客户端路由。使用
@tanstack/router-plugin
实现基于文件的路由,自动生成路由树。通过
@tanstack/zod-adapter
结合Zod定义搜索参数。使用
loader
进行数据获取,
beforeLoad
实现守卫/重定向,
createRootRouteWithContext
进行依赖注入。版本:v1.x(稳定版)。

<critical_requirements>

CRITICAL: Before Using This Skill

重要提示:使用此技能前须知

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type
, named constants)
(You MUST use
createFileRoute
for all file-based routes - NEVER define routes manually when using the router plugin)
(You MUST validate search params with
validateSearch
- NEVER read raw
window.location.search
)
(You MUST use
beforeLoad
for auth guards and redirects - NEVER check auth inside component render)
(You MUST pass services via router context - NEVER import them directly in loaders (breaks testability))
(You MUST use
<Outlet />
in layout routes to render child content - forgetting it renders nothing)
</critical_requirements>

Auto-detection: TanStack Router, createFileRoute, createRootRoute, createRootRouteWithContext, createRouter, RouterProvider, Outlet, useNavigate, useSearch, useParams, useLoaderData, useRouteContext, routeTree.gen, tanstack/react-router, tanstack/router-plugin, validateSearch, zodValidator, beforeLoad, loader, notFound, redirect
When to use:
  • Building React SPAs with type-safe client-side routing
  • File-based routing with automatic route tree generation
  • Validated and type-safe URL search parameters
  • Route-level data loading with caching
  • Nested layouts with shared UI across child routes
  • Authentication guards and route protection
  • Code splitting routes for performance
Key patterns covered:
  • File-based routing setup with Vite plugin
  • Route definitions (
    createFileRoute
    ,
    createRootRoute
    )
  • Type-safe navigation (
    Link
    ,
    useNavigate
    ,
    redirect
    )
  • Search params validation with Zod
  • Route loaders and
    beforeLoad
    middleware
  • Nested layouts and pathless layout routes
  • Route context and dependency injection
  • Authentication guards and protected routes
  • Code splitting with
    autoCodeSplitting
  • Error, pending, and not-found handling
  • External data fetching library integration in loaders
  • Devtools setup
When NOT to use:
  • Server-rendered apps with SSR needs (use an SSR framework instead)
  • Simple apps with 1-2 pages (a lightweight router or no router)
  • Static sites without client-side navigation

所有代码必须遵循CLAUDE.md中的项目规范(短横线命名、命名导出、导入顺序、
import type
、命名常量)
(使用路由插件时,必须为所有基于文件的路由使用
createFileRoute
——绝不要手动定义路由)
(必须使用
validateSearch
验证搜索参数——绝不要直接读取
window.location.search
)
(必须使用
beforeLoad
实现鉴权守卫和重定向——绝不要在组件渲染时检查鉴权)
(必须通过路由上下文传递服务——绝不要在加载器中直接导入服务(会破坏可测试性))
(必须在布局路由中使用
<Outlet />
渲染子内容——遗漏会导致无内容渲染)
</critical_requirements>

自动检测项: TanStack Router, createFileRoute, createRootRoute, createRootRouteWithContext, createRouter, RouterProvider, Outlet, useNavigate, useSearch, useParams, useLoaderData, useRouteContext, routeTree.gen, tanstack/react-router, tanstack/router-plugin, validateSearch, zodValidator, beforeLoad, loader, notFound, redirect
适用场景:
  • 构建带有类型安全客户端路由的React单页应用(SPA)
  • 带有自动路由树生成的基于文件的路由
  • 经过验证的类型安全URL搜索参数
  • 带缓存的路由级数据加载
  • 子路由共享UI的嵌套布局
  • 鉴权守卫和路由保护
  • 路由代码分割以提升性能
涵盖的核心模式:
  • 结合Vite插件的基于文件的路由设置
  • 路由定义(
    createFileRoute
    、
    createRootRoute
    )
  • 类型安全导航(
    Link
    、
    useNavigate
    、
    redirect
    )
  • 基于Zod的搜索参数验证
  • 路由加载器和
    beforeLoad
    中间件
  • 嵌套布局和无路径布局路由
  • 路由上下文和依赖注入
  • 鉴权守卫和受保护路由
  • 结合
    autoCodeSplitting
    的代码分割
  • 错误、加载中和未找到页面的处理
  • 加载器中集成外部数据获取库
  • 开发者工具设置
不适用场景:
  • 需要服务端渲染(SSR)的服务端渲染应用(请使用SSR框架)
  • 只有1-2个页面的简单应用(使用轻量路由或无需路由)
  • 无客户端导航的静态站点

Examples

示例

  • Core Setup & Configuration -- Vite plugin, root route, entry point, devtools
  • Routes & Layouts -- file-based routing conventions, nested layouts, pathless routes, catch-all
  • Navigation -- Link component, useNavigate, redirect, active states
  • Data Loading -- loaders, beforeLoad, external data fetching integration, SWR caching
  • Search Params -- Zod validation, updating params, search middleware
  • Auth & Context -- auth guards, route context, dependency injection, getRouteApi
  • Error Handling & Code Splitting -- error/pending/not-found components, code splitting
For quick API reference (hooks, components, route options), see reference.md.

<philosophy>
  • 核心设置与配置 -- Vite插件、根路由、入口点、开发者工具
  • 路由与布局 -- 基于文件的路由规范、嵌套布局、无路径路由、兜底路由
  • 导航 -- Link组件、useNavigate、redirect、激活状态
  • 数据加载 -- 加载器、beforeLoad、外部数据获取集成、SWR缓存
  • 搜索参数 -- Zod验证、更新参数、搜索中间件
  • 鉴权与上下文 -- 鉴权守卫、路由上下文、依赖注入、getRouteApi
  • 错误处理与代码分割 -- 错误/加载中/未找到组件、代码分割
如需快速API参考(钩子、组件、路由选项),请查看reference.md。

<philosophy>

Philosophy

设计理念

TanStack Router treats the URL as a first-class, fully-typed state manager. Every path parameter, search parameter, and loader return type is inferred through TypeScript, catching routing bugs at compile time rather than runtime. The router plugin generates a route tree from your file system, giving you type-safe
<Link>
components and
useNavigate
calls that validate destinations, params, and search params automatically.
Core principles:
  • URL is typed state - Search params are validated schemas, not raw strings
  • File system is the route tree - Convention over configuration via
    @tanstack/router-plugin
  • Loaders run before render - Data is available when the component mounts, not after
  • Context flows down - Dependency injection through
    createRootRouteWithContext
    , not global imports
  • Parallel by default - Sibling route loaders run in parallel, not waterfall
When to use TanStack Router:
  • React SPAs needing type-safe routing across the entire app
  • Apps with complex search param state (filters, pagination, sorting)
  • Apps requiring route-level data loading with SWR caching
  • Projects that benefit from file-based routing conventions
  • Teams that value compile-time route validation
When NOT to use:
  • Full-stack SSR apps (use an SSR/full-stack framework instead)
  • Micro-frontends or embedded widgets with no routing needs
  • Static marketing sites with no client-side navigation
</philosophy>
<patterns>
TanStack Router 将URL视为一等公民的完全类型化状态管理器。每个路径参数、搜索参数和加载器返回类型都通过TypeScript推断,在编译时而非运行时捕获路由错误。路由插件从文件系统生成路由树,提供自动验证目标、参数和搜索参数的类型安全
<Link>
组件和
useNavigate
调用。
核心原则:
  • URL是类型化状态 - 搜索参数是经过验证的模式,而非原始字符串
  • 文件系统即路由树 - 通过
    @tanstack/router-plugin
    实现约定优于配置
  • 加载器在渲染前运行 - 组件挂载时数据已就绪,而非之后
  • 上下文向下流动 - 通过
    createRootRouteWithContext
    实现依赖注入,而非全局导入
  • 默认并行执行 - 兄弟路由加载器并行运行,而非瀑布式执行
何时使用TanStack Router:
  • 整个应用需要类型安全路由的React SPA
  • 带有复杂搜索参数状态(筛选、分页、排序)的应用
  • 需要路由级数据加载并结合SWR缓存的应用
  • 能从基于文件的路由规范中获益的项目
  • 重视编译时路由验证的团队
何时不使用:
  • 全栈SSR应用(请使用SSR/全栈框架)
  • 无路由需求的微前端或嵌入组件
  • 无客户端导航的静态营销站点
</philosophy>
<patterns>

Core Patterns

核心模式

Pattern 1: Project Setup

模式1:项目设置

Install
@tanstack/react-router
,
@tanstack/router-plugin
, and optionally
@tanstack/zod-adapter
. Configure the Vite plugin with
autoCodeSplitting: true
before the React plugin. Register the router via
declare module
for app-wide type safety.
typescript
// vite.config.ts - Router plugin MUST come before React plugin
tanstackRouter({ target: "react", autoCodeSplitting: true }),
react(),
typescript
// src/main.tsx - Register for type safety
const router = createRouter({ routeTree });
declare module "@tanstack/react-router" {
  interface Register {
    router: typeof router;
  }
}
See examples/core.md for complete setup with context and devtools.

安装
@tanstack/react-router
、
@tanstack/router-plugin
,可选安装
@tanstack/zod-adapter
。在React插件之前配置Vite插件并设置
autoCodeSplitting: true
。通过
declare module
注册路由以实现全应用类型安全。
typescript
// vite.config.ts - 路由插件必须在React插件之前
 tanstackRouter({ target: "react", autoCodeSplitting: true }),
 react(),
typescript
// src/main.tsx - 注册以实现类型安全
const router = createRouter({ routeTree });
declare module "@tanstack/react-router" {
  interface Register {
    router: typeof router;
  }
}
完整的上下文和开发者工具设置请查看examples/core.md。

Pattern 2: File-Based Routing Conventions

模式2:基于文件的路由规范

The router plugin generates a typed route tree from your file structure. Key conventions:
ConventionExamplePurpose
__root.tsx
__root.tsx
Root layout, wraps entire app
index.tsx
posts/index.tsx
Index route for directory (
/posts
)
$param
$postId/index.tsx
Dynamic path parameter
_prefix
_authenticated.tsx
Pathless layout (no URL segment)
route.tsx
posts/route.tsx
Layout for directory children
suffix_
posts_.detail.tsx
Non-nested route (escapes parent layout)
$
$.tsx
Splat/catch-all route
-prefix
-components.tsx
Ignored by router (not a route)
(group)
(admin)/
Organizational grouping (no URL effect)
typescript
// src/routes/posts/index.tsx
export const Route = createFileRoute("/posts/")({
  component: PostsIndex,
});
See examples/routes.md for nested layouts, pathless routes, non-nested routes, and catch-all routes.

路由插件从文件结构生成类型化路由树。核心规范:
规范示例用途
__root.tsx
__root.tsx
根布局,包裹整个应用
index.tsx
posts/index.tsx
目录的索引路由(对应
/posts
)
$param
$postId/index.tsx
动态路径参数
_prefix
_authenticated.tsx
无路径布局(不生成URL片段)
route.tsx
posts/route.tsx
目录子路由的布局
suffix_
posts_.detail.tsx
非嵌套路由(脱离父布局)
$
$.tsx
通配/兜底路由
-prefix
-components.tsx
被路由忽略(不视为路由)
(group)
(admin)/
组织分组(不影响URL)
typescript
// src/routes/posts/index.tsx
export const Route = createFileRoute("/posts/")({
  component: PostsIndex,
});
嵌套布局、无路径路由、非嵌套路由和兜底路由请查看examples/routes.md。

Pattern 3: Type-Safe Navigation

模式3:类型安全导航

TanStack Router validates all navigation destinations, params, and search params at compile time.
typescript
// Declarative - Link component
<Link to="/posts/$postId" params={{ postId: post.id }} preload="intent">
  {post.title}
</Link>

// Imperative - after side effects
const navigate = useNavigate();
await navigate({ to: "/posts/$postId", params: { postId: post.id }, replace: true });

// In loaders/beforeLoad - redirect
throw redirect({ to: "/login", search: { redirect: location.href } });
See examples/navigation.md for active states, search param updaters, and navigation decision tree.

TanStack Router在编译时验证所有导航目标、参数和搜索参数。
typescript
// 声明式 - Link组件
<Link to="/posts/$postId" params={{ postId: post.id }} preload="intent">
  {post.title}
</Link>

// 命令式 - 副作用之后
const navigate = useNavigate();
await navigate({ to: "/posts/$postId", params: { postId: post.id }, replace: true });

// 在加载器/beforeLoad中 - 重定向
throw redirect({ to: "/login", search: { redirect: location.href } });
激活状态、搜索参数更新器和导航决策树请查看examples/navigation.md。

Pattern 4: Search Params Validation

模式4:搜索参数验证

Validate and type search params with
validateSearch
. Use Zod adapter for schema-based validation with
fallback()
for safe defaults.
typescript
import { zodValidator, fallback } from "@tanstack/zod-adapter";

const DEFAULT_PAGE = 1;
const schema = z.object({
  page: fallback(z.number().min(1), DEFAULT_PAGE).default(DEFAULT_PAGE),
  q: fallback(z.string(), "").default(""),
});

export const Route = createFileRoute("/products/")({
  validateSearch: zodValidator(schema),
  component: ProductsPage,
});

// In component: fully typed
const { page, q } = Route.useSearch();
See examples/search-params.md for complete filter pages, search middleware, plain function validation, and declarative vs imperative updates.

使用
validateSearch
验证并类型化搜索参数。结合Zod适配器实现基于模式的验证,使用
fallback()
设置安全默认值。
typescript
import { zodValidator, fallback } from "@tanstack/zod-adapter";

const DEFAULT_PAGE = 1;
const schema = z.object({
  page: fallback(z.number().min(1), DEFAULT_PAGE).default(DEFAULT_PAGE),
  q: fallback(z.string(), "").default(""),
});

export const Route = createFileRoute("/products/")({
  validateSearch: zodValidator(schema),
  component: ProductsPage,
});

// 在组件中:完全类型化
const { page, q } = Route.useSearch();
完整的筛选页面、搜索中间件、普通函数验证以及声明式与命令式更新请查看examples/search-params.md。

Pattern 5: Route Loaders and Data Loading

模式5:路由加载器与数据加载

Loaders fetch data before the component renders. They run in parallel for sibling routes and support SWR-style caching.
typescript
export const Route = createFileRoute("/posts/$postId/")({
  staleTime: STALE_TIME_MS,
  loader: async ({ params, context, abortController }) => {
    const post = await context.apiClient.getPost(params.postId, {
      signal: abortController.signal,
    });
    return { post };
  },
  component: PostDetail,
});

// Data is guaranteed available - no loading state needed
const { post } = Route.useLoaderData();
beforeLoad runs first (sequentially) for auth checks and context enrichment. loader runs after (in parallel with siblings) for data fetching.
See examples/data-loading.md for external data fetching integration, non-blocking prefetch, and SWR caching.

加载器在组件渲染前获取数据。兄弟路由的加载器并行运行,并支持SWR风格的缓存。
typescript
export const Route = createFileRoute("/posts/$postId/")({
  staleTime: STALE_TIME_MS,
  loader: async ({ params, context, abortController }) => {
    const post = await context.apiClient.getPost(params.postId, {
      signal: abortController.signal,
    });
    return { post };
  },
  component: PostDetail,
});

// 数据保证可用 - 无需加载状态
const { post } = Route.useLoaderData();
beforeLoad先执行(顺序执行),用于鉴权检查和上下文增强。loader在之后执行(与兄弟路由并行),用于数据获取。
外部数据获取集成、非阻塞预取和SWR缓存请查看examples/data-loading.md。

Pattern 6: Nested Layouts and Outlets

模式6:嵌套布局与Outlet

Layout routes wrap child routes with shared UI. Use
<Outlet />
to render matched child content.
typescript
// src/routes/posts/route.tsx - Layout for /posts/*
export const Route = createFileRoute("/posts")({
  component: () => (
    <div className="posts-layout">
      <aside>{/* Sidebar */}</aside>
      <Outlet /> {/* Renders child route */}
    </div>
  ),
});
Pathless layouts (
_prefix
) add UI/guards without affecting the URL:
typescript
// src/routes/_authenticated.tsx -> children at /dashboard, /settings (no /_authenticated in URL)
export const Route = createFileRoute("/_authenticated")({
  beforeLoad: async ({ context }) => {
    if (!context.auth.isAuthenticated) throw redirect({ to: "/login" });
  },
  component: () => <Outlet />,
});
See examples/routes.md for nested pathless layouts, non-nested routes, and catch-all routes.

布局路由使用共享UI包裹子路由。使用
<Outlet />
渲染匹配的子内容。
typescript
// src/routes/posts/route.tsx - /posts/*的布局
export const Route = createFileRoute("/posts")({
  component: () => (
    <div className="posts-layout">
      <aside>{/* 侧边栏 */}</aside>
      <Outlet /> {/* 渲染子路由 */}
    </div>
  ),
});
无路径布局(
_prefix
)添加UI/守卫但不影响URL:
typescript
// src/routes/_authenticated.tsx -> 子路由位于/dashboard、/settings(URL中无/_authenticated)
export const Route = createFileRoute("/_authenticated")({
  beforeLoad: async ({ context }) => {
    if (!context.auth.isAuthenticated) throw redirect({ to: "/login" });
  },
  component: () => <Outlet />,
});
嵌套无路径布局、非嵌套路由和兜底路由请查看examples/routes.md。

Pattern 7: Route Context and Dependency Injection

模式7:路由上下文与依赖注入

Use
createRootRouteWithContext
to inject dependencies (auth, data clients, services) into all routes via typed context.
typescript
// Root: define context shape
export const Route = createRootRouteWithContext<RouterContext>()({
  component: RootLayout,
});

// Entry: provide context
const router = createRouter({
  routeTree,
  context: { auth: authService, apiClient },
});

// Routes: access typed context in loaders
loader: async ({ context }) => {
  const posts = await context.apiClient.getPosts();
  return { posts };
};
See examples/auth-and-context.md for complete patterns including context enrichment via
beforeLoad
and
getRouteApi
for shared components.

使用
createRootRouteWithContext
将依赖项(鉴权、数据客户端、服务)通过类型化上下文注入所有路由。
typescript
// 根路由:定义上下文结构
export const Route = createRootRouteWithContext<RouterContext>()({
  component: RootLayout,
});

// 入口:提供上下文
const router = createRouter({
  routeTree,
  context: { auth: authService, apiClient },
});

// 路由:在加载器中访问类型化上下文
loader: async ({ context }) => {
  const posts = await context.apiClient.getPosts();
  return { posts };
};
完整模式包括通过
beforeLoad
增强上下文和为共享组件使用
getRouteApi
,请查看examples/auth-and-context.md。

Pattern 8: Error, Pending, and Not-Found Handling

模式8:错误、加载中和未找到页面处理

typescript
const PENDING_DELAY_MS = 200;

export const Route = createFileRoute("/posts/$postId/")({
  pendingMs: PENDING_DELAY_MS,
  pendingComponent: () => <div>Loading...</div>,
  errorComponent: ({ error, reset }) => (
    <div role="alert">
      <pre>{error.message}</pre>
      <button type="button" onClick={reset}>Retry</button>
    </div>
  ),
  notFoundComponent: () => <div>Post not found</div>,
  loader: async ({ params }) => {
    const post = await fetchPost(params.postId);
    if (!post) throw notFound();
    return { post };
  },
  component: PostDetail,
});
See examples/error-handling.md for router-level defaults, code splitting strategies, and preloading.
</patterns>
<decision_framework>
typescript
const PENDING_DELAY_MS = 200;

export const Route = createFileRoute("/posts/$postId/")({
  pendingMs: PENDING_DELAY_MS,
  pendingComponent: () => <div>加载中...</div>,
  errorComponent: ({ error, reset }) => (
    <div role="alert">
      <pre>{error.message}</pre>
      <button type="button" onClick={reset}>重试</button>
    </div>
  ),
  notFoundComponent: () => <div>文章未找到</div>,
  loader: async ({ params }) => {
    const post = await fetchPost(params.postId);
    if (!post) throw notFound();
    return { post };
  },
  component: PostDetail,
});
路由级默认设置、代码分割策略和预加载请查看examples/error-handling.md。
</patterns>
<decision_framework>

Decision Framework

决策框架

When to Use Each Navigation Method

何时使用每种导航方式

Need to navigate?
  +-- Is it a clickable element in JSX?
  |   +-- YES -> Use <Link to="..." />
  |   +-- NO -> Is it after a side effect (form submit, mutation)?
  |       +-- YES -> Use useNavigate()
  |       +-- NO -> Is it in a loader/beforeLoad?
  |           +-- YES -> throw redirect()
  |           +-- NO -> Use router.navigate()
需要导航?
  +-- 是否是JSX中的可点击元素?
  |   +-- 是 -> 使用<Link to="..." />
  |   +-- 否 -> 是否是在副作用之后(表单提交、修改操作)?
  |       +-- 是 -> 使用useNavigate()
  |       +-- 否 -> 是否在loader/beforeLoad中?
  |           +-- 是 -> throw redirect()
  |           +-- 否 -> 使用router.navigate()

Where to Put Logic: beforeLoad vs loader

逻辑放置:beforeLoad vs loader

What does the logic do?
  +-- Auth check / permission guard?
  |   -> beforeLoad (blocks everything, runs first)
  +-- Redirect based on conditions?
  |   -> beforeLoad (throw redirect())
  +-- Add data to context for children?
  |   -> beforeLoad (return value merges into context)
  +-- Fetch data for the component?
  |   -> loader (runs in parallel with siblings)
  +-- Prefetch data for an external cache?
  |   -> loader (prefetch via context-injected client, runs in parallel)
逻辑的作用是什么?
  +-- 鉴权检查/权限守卫?
  |   -> beforeLoad(阻止所有操作,优先运行)
  +-- 根据条件重定向?
  |   -> beforeLoad(throw redirect())
  +-- 为子路由添加上下文数据?
  |   -> beforeLoad(返回值合并到上下文)
  +-- 为组件获取数据?
  |   -> loader(与兄弟路由并行运行)
  +-- 为外部缓存预取数据?
  |   -> loader(通过上下文注入的客户端预取,并行运行)

Data Loading Strategy

数据加载策略

How to load data?
  +-- Simple app, no shared cache needs?
  |   -> Built-in route loaders with staleTime
  +-- Complex app with shared server state cache?
  |   -> External data fetching library + prefetch in loaders
  +-- Data needed only for this component?
  |   -> Route loader (useLoaderData)
  +-- Data shared across many components?
  |   -> External data fetching library (client in context)
如何加载数据?
  +-- 简单应用,无共享缓存需求?
  |   -> 带staleTime的内置路由加载器
  +-- 复杂应用,带共享服务端状态缓存?
  |   -> 外部数据获取库 + 加载器中预取
  +-- 仅当前组件需要的数据?
  |   -> 路由加载器(useLoaderData)
  +-- 多个组件共享的数据?
  |   -> 外部数据获取库(上下文提供客户端)

Search Params: Zod Adapter vs Plain Function

搜索参数:Zod适配器 vs 普通函数

Validating search params?
  +-- Complex schema with many fields?
  |   -> Zod adapter (zodValidator + fallback)
  +-- Simple 1-2 params?
  |   -> Plain validateSearch function
  +-- Need shared schema with forms?
  |   -> Zod adapter (share schema between route and form)
  +-- Zod 3.24.0+ / Zod 4+ with Standard Schema?
  |   -> Can use Zod directly without adapter (use `.catch()` for defaults)
验证搜索参数?
  +-- 多字段的复杂模式?
  |   -> Zod适配器(zodValidator + fallback)
  +-- 1-2个简单参数?
  |   -> 普通validateSearch函数
  +-- 需要与表单共享模式?
  |   -> Zod适配器(路由与表单共享模式)
  +-- Zod 3.24.0+ / 带标准模式的Zod 4+?
  |   -> 无需适配器直接使用Zod(使用`.catch()`设置默认值)

Layout Strategy

布局策略

Need shared UI across routes?
  +-- Shared UI for a URL segment (/posts/*)?
  |   -> route.tsx in directory (posts/route.tsx)
  +-- Shared UI without URL segment (auth guard)?
  |   -> Pathless layout (_authenticated.tsx)
  +-- Route should escape parent layout?
  |   -> Non-nested route suffix (posts_.detail.tsx)
  +-- Organizational grouping only?
  |   -> Group directory ((admin)/)
</decision_framework>

<integration>
路由需要共享UI?
  +-- URL片段对应的共享UI(/posts/*)?
  |   -> 目录中的route.tsx(posts/route.tsx)
  +-- 无URL片段的共享UI(鉴权守卫)?
  |   -> 无路径布局(_authenticated.tsx)
  +-- 路由需要脱离父布局?
  |   -> 非嵌套路由后缀(posts_.detail.tsx)
  +-- 仅用于组织分组?
  |   -> 分组目录((admin)/)
</decision_framework>

<integration>

Integration Guide

集成指南

Package ecosystem:
PackagePurpose
@tanstack/react-router
Core router for React
@tanstack/router-plugin
Vite/Webpack plugin for file-based routing
@tanstack/react-router-devtools
Development tools
@tanstack/zod-adapter
Zod integration for search params
@tanstack/valibot-adapter
Valibot integration for search params
Schema validation adapters: Use
@tanstack/zod-adapter
or
@tanstack/valibot-adapter
for search params. Zod 3.24.0+ supports Standard Schema and can be used directly without an adapter.
External data fetching: The router context system (
createRootRouteWithContext
) enables injecting any data fetching client. Loaders can prefetch data via
context
, and components consume cached data. See examples/data-loading.md.
Conflicts with other client routers: TanStack Router replaces any other client-side routing solution. Do not combine with another router library.
</integration>
<red_flags>
包生态:
包名称用途
@tanstack/react-router
React核心路由库
@tanstack/router-plugin
用于基于文件路由的Vite/Webpack插件
@tanstack/react-router-devtools
开发工具
@tanstack/zod-adapter
搜索参数的Zod集成
@tanstack/valibot-adapter
搜索参数的Valibot集成
模式验证适配器: 使用
@tanstack/zod-adapter
或
@tanstack/valibot-adapter
处理搜索参数。Zod 3.24.0+支持标准模式,无需适配器即可直接使用。
外部数据获取: 路由上下文系统(
createRootRouteWithContext
)支持注入任何数据获取客户端。加载器可通过
context
预取数据,组件消费缓存数据。请查看examples/data-loading.md。
与其他客户端路由的冲突: TanStack Router替代任何其他客户端路由解决方案。请勿与其他路由库混用。
</integration>
<red_flags>

RED FLAGS

注意事项

High Priority Issues:
  • Defining routes manually with
    createRoute
    when using file-based routing plugin (routes will be out of sync with generated tree)
  • Reading
    window.location.search
    directly instead of
    useSearch()
    (bypasses validation, breaks SSR, loses reactivity)
  • Checking auth inside component render instead of
    beforeLoad
    (component flashes before redirect, race conditions)
  • Forgetting
    <Outlet />
    in layout routes (child routes render nothing)
  • Importing services/clients directly in loaders instead of using router context (breaks testability, couples to global state)
Medium Priority Issues:
  • Awaiting non-critical data in loaders (blocks render unnecessarily - fire-and-forget prefetch for non-critical data)
  • Not using
    fallback()
    with Zod adapter (invalid search params throw errors instead of falling back to defaults)
  • Missing
    declare module "@tanstack/react-router"
    registration (Link, navigate lose type safety across the app)
  • Duplicating auth checks in every route instead of using a pathless layout guard
  • Using
    staleTime: 0
    when an external data cache handles freshness (double-fetching on every navigation)
Common Mistakes:
  • Putting data-fetching logic in
    beforeLoad
    instead of
    loader
    (creates waterfalls,
    beforeLoad
    runs sequentially)
  • Forgetting to pass
    context
    when creating the router (TypeScript error if using
    createRootRouteWithContext
    )
  • Using
    to="."
    without
    from
    in child components (path resolution may be wrong)
  • Not handling the
    redirect
    search param in the login page (users lose their intended destination)
Gotchas and Edge Cases:
  • beforeLoad
    runs sequentially (parent before child) while
    loader
    runs in parallel - heavy work in
    beforeLoad
    creates waterfalls
  • The
    routeTree.gen.ts
    file is auto-generated - never edit it manually, it will be overwritten
  • createFileRoute
    path string must exactly match the file's location in the routes directory
  • Search params are serialized to the URL - avoid large objects, binary data, or sensitive information
  • notFound()
    and
    redirect()
    must be thrown, not returned
  • The router plugin must be listed before the React plugin in Vite config
  • useSearch({ strict: false })
    returns a partial type - only use when you genuinely do not know which route you are on
  • Path params (
    $postId
    ) are always strings - cast to number in the loader if needed, not in the component
</red_flags>

<critical_reminders>
高优先级问题:
  • 使用基于文件的路由插件时,手动用
    createRoute
    定义路由(路由会与生成的树不同步)
  • 直接读取
    window.location.search
    而非
    useSearch()
    (绕过验证,破坏SSR,失去响应性)
  • 在组件渲染时检查鉴权而非使用
    beforeLoad
    (组件在重定向前会闪烁,存在竞态条件)
  • 布局路由中遗漏
    <Outlet />
    (子路由无内容渲染)
  • 在加载器中直接导入服务/客户端而非使用路由上下文(破坏可测试性,耦合到全局状态)
中优先级问题:
  • 在加载器中等待非关键数据(不必要地阻塞渲染——对非关键数据使用即发即弃的预取)
  • 使用Zod适配器时未使用
    fallback()
    (无效搜索参数会抛出错误而非回退到默认值)
  • 遗漏
    declare module "@tanstack/react-router"
    注册(Link、navigate失去全应用类型安全)
  • 在每个路由中重复鉴权检查而非使用无路径布局守卫
  • 当外部数据缓存处理新鲜度时使用
    staleTime: 0
    (每次导航都会重复获取)
常见错误:
  • 将数据获取逻辑放在
    beforeLoad
    而非
    loader
    中(导致瀑布流,
    beforeLoad
    顺序执行)
  • 创建路由时忘记传递
    context
    (使用
    createRootRouteWithContext
    会触发TypeScript错误)
  • 在子组件中使用
    to="."
    而未指定
    from
    (路径解析可能错误)
  • 登录页面未处理
    redirect
    搜索参数(用户丢失目标页面)
陷阱与边缘情况:
  • beforeLoad
    顺序执行(父路由先于子路由),而
    loader
    并行执行——
    beforeLoad
    中的繁重工作会导致瀑布流
  • routeTree.gen.ts
    文件自动生成——绝不要手动编辑,会被覆盖
  • createFileRoute
    路径字符串必须与文件在routes目录中的位置完全匹配
  • 搜索参数会序列化为URL——避免大对象、二进制数据或敏感信息
  • notFound()
    和
    redirect()
    必须抛出,而非返回
  • Vite配置中路由插件必须在React插件之前
  • useSearch({ strict: false })
    返回部分类型——仅在确实不知道当前路由时使用
  • 路径参数(
    $postId
    )始终是字符串——如需数字请在加载器中转换,而非在组件中
</red_flags>

<critical_reminders>

CRITICAL REMINDERS

重要提醒

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type
, named constants)
(You MUST use
createFileRoute
for all file-based routes - NEVER define routes manually when using the router plugin)
(You MUST validate search params with
validateSearch
- NEVER read raw
window.location.search
)
(You MUST use
beforeLoad
for auth guards and redirects - NEVER check auth inside component render)
(You MUST pass services via router context - NEVER import them directly in loaders (breaks testability))
(You MUST use
<Outlet />
in layout routes to render child content - forgetting it renders nothing)
Failure to follow these rules will break type safety, create security vulnerabilities in auth flows, and cause routes to silently render nothing.
</critical_reminders>
所有代码必须遵循CLAUDE.md中的项目规范(短横线命名、命名导出、导入顺序、
import type
、命名常量)
(使用路由插件时,必须为所有基于文件的路由使用
createFileRoute
——绝不要手动定义路由)
(必须使用
validateSearch
验证搜索参数——绝不要直接读取
window.location.search
)
(必须使用
beforeLoad
实现鉴权守卫和重定向——绝不要在组件渲染时检查鉴权)
(必须通过路由上下文传递服务——绝不要在加载器中直接导入服务(会破坏可测试性))
(必须在布局路由中使用
<Outlet />
渲染子内容——遗漏会导致无内容渲染)
不遵循这些规则会破坏类型安全,在鉴权流程中产生安全漏洞,并导致路由无提示地无法渲染内容。
</critical_reminders>