web-routing-tanstack-router
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseTanStack Router Patterns
TanStack Router 模式
Quick Guide: TanStack Router provides fully type-safe client-side routing for React. Use file-based routing withfor automatic route tree generation. Define search params with Zod via@tanstack/router-plugin. Use@tanstack/zod-adapterfor data fetching,loaderfor guards/redirects, andbeforeLoadfor dependency injection. Version: v1.x (stable).createRootRouteWithContext
<critical_requirements>
快速指南: TanStack Router 为React提供完全类型安全的客户端路由。使用实现基于文件的路由,自动生成路由树。通过@tanstack/router-plugin结合Zod定义搜索参数。使用@tanstack/zod-adapter进行数据获取,loader实现守卫/重定向,beforeLoad进行依赖注入。版本:v1.x(稳定版)。createRootRouteWithContext
<critical_requirements>
CRITICAL: Before Using This Skill
重要提示:使用此技能前须知
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,, named constants)import type
(You MUST use for all file-based routes - NEVER define routes manually when using the router plugin)
createFileRoute(You MUST validate search params with - NEVER read raw )
validateSearchwindow.location.search(You MUST use for auth guards and redirects - NEVER check auth inside component render)
beforeLoad(You MUST pass services via router context - NEVER import them directly in loaders (breaks testability))
(You MUST use in layout routes to render child content - forgetting it renders nothing)
<Outlet /></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 middleware
beforeLoad - 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(必须使用验证搜索参数——绝不要直接读取)
validateSearchwindow.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 components and calls that validate destinations, params, and search params automatically.
<Link>useNavigateCore 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 , not global imports
createRootRouteWithContext - 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
<patterns>
TanStack Router 将URL视为一等公民的完全类型化状态管理器。每个路径参数、搜索参数和加载器返回类型都通过TypeScript推断,在编译时而非运行时捕获路由错误。路由插件从文件系统生成路由树,提供自动验证目标、参数和搜索参数的类型安全组件和调用。
<Link>useNavigate核心原则:
- URL是类型化状态 - 搜索参数是经过验证的模式,而非原始字符串
- 文件系统即路由树 - 通过实现约定优于配置
@tanstack/router-plugin - 加载器在渲染前运行 - 组件挂载时数据已就绪,而非之后
- 上下文向下流动 - 通过实现依赖注入,而非全局导入
createRootRouteWithContext - 默认并行执行 - 兄弟路由加载器并行运行,而非瀑布式执行
何时使用TanStack Router:
- 整个应用需要类型安全路由的React SPA
- 带有复杂搜索参数状态(筛选、分页、排序)的应用
- 需要路由级数据加载并结合SWR缓存的应用
- 能从基于文件的路由规范中获益的项目
- 重视编译时路由验证的团队
何时不使用:
- 全栈SSR应用(请使用SSR/全栈框架)
- 无路由需求的微前端或嵌入组件
- 无客户端导航的静态营销站点
<patterns>
Core Patterns
核心模式
Pattern 1: Project Setup
模式1:项目设置
Install , , and optionally . Configure the Vite plugin with before the React plugin. Register the router via for app-wide type safety.
@tanstack/react-router@tanstack/router-plugin@tanstack/zod-adapterautoCodeSplitting: truedeclare moduletypescript
// 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.
安装、,可选安装。在React插件之前配置Vite插件并设置。通过注册路由以实现全应用类型安全。
@tanstack/react-router@tanstack/router-plugin@tanstack/zod-adapterautoCodeSplitting: truedeclare moduletypescript
// 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:
| Convention | Example | Purpose |
|---|---|---|
| | Root layout, wraps entire app |
| | Index route for directory ( |
| | Dynamic path parameter |
| | Pathless layout (no URL segment) |
| | Layout for directory children |
| | Non-nested route (escapes parent layout) |
| | Splat/catch-all route |
| | Ignored by router (not a route) |
| | 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.
路由插件从文件结构生成类型化路由树。核心规范:
| 规范 | 示例 | 用途 |
|---|---|---|
| | 根布局,包裹整个应用 |
| | 目录的索引路由(对应 |
| | 动态路径参数 |
| | 无路径布局(不生成URL片段) |
| | 目录子路由的布局 |
| | 非嵌套路由(脱离父布局) |
| | 通配/兜底路由 |
| | 被路由忽略(不视为路由) |
| | 组织分组(不影响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 . Use Zod adapter for schema-based validation with for safe defaults.
validateSearchfallback()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.
使用验证并类型化搜索参数。结合Zod适配器实现基于模式的验证,使用设置安全默认值。
validateSearchfallback()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 to render matched child content.
<Outlet />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 () add UI/guards without affecting the URL:
_prefixtypescript
// 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>
),
});无路径布局()添加UI/守卫但不影响URL:
_prefixtypescript
// 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 to inject dependencies (auth, data clients, services) into all routes via typed context.
createRootRouteWithContexttypescript
// 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 and for shared components.
beforeLoadgetRouteApi使用将依赖项(鉴权、数据客户端、服务)通过类型化上下文注入所有路由。
createRootRouteWithContexttypescript
// 根路由:定义上下文结构
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 };
};完整模式包括通过增强上下文和为共享组件使用,请查看examples/auth-and-context.md。
beforeLoadgetRouteApiPattern 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:
| Package | Purpose |
|---|---|
| Core router for React |
| Vite/Webpack plugin for file-based routing |
| Development tools |
| Zod integration for search params |
| Valibot integration for search params |
Schema validation adapters: Use or for search params. Zod 3.24.0+ supports Standard Schema and can be used directly without an adapter.
@tanstack/zod-adapter@tanstack/valibot-adapterExternal data fetching: The router context system () enables injecting any data fetching client. Loaders can prefetch data via , and components consume cached data. See examples/data-loading.md.
createRootRouteWithContextcontextConflicts with other client routers: TanStack Router replaces any other client-side routing solution. Do not combine with another router library.
</integration>
<red_flags>
包生态:
| 包名称 | 用途 |
|---|---|
| React核心路由库 |
| 用于基于文件路由的Vite/Webpack插件 |
| 开发工具 |
| 搜索参数的Zod集成 |
| 搜索参数的Valibot集成 |
模式验证适配器: 使用或处理搜索参数。Zod 3.24.0+支持标准模式,无需适配器即可直接使用。
@tanstack/zod-adapter@tanstack/valibot-adapter外部数据获取: 路由上下文系统()支持注入任何数据获取客户端。加载器可通过预取数据,组件消费缓存数据。请查看examples/data-loading.md。
createRootRouteWithContextcontext与其他客户端路由的冲突: TanStack Router替代任何其他客户端路由解决方案。请勿与其他路由库混用。
</integration>
<red_flags>
RED FLAGS
注意事项
High Priority Issues:
- Defining routes manually with when using file-based routing plugin (routes will be out of sync with generated tree)
createRoute - Reading directly instead of
window.location.search(bypasses validation, breaks SSR, loses reactivity)useSearch() - Checking auth inside component render instead of (component flashes before redirect, race conditions)
beforeLoad - Forgetting in layout routes (child routes render nothing)
<Outlet /> - 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 with Zod adapter (invalid search params throw errors instead of falling back to defaults)
fallback() - Missing registration (Link, navigate lose type safety across the app)
declare module "@tanstack/react-router" - Duplicating auth checks in every route instead of using a pathless layout guard
- Using when an external data cache handles freshness (double-fetching on every navigation)
staleTime: 0
Common Mistakes:
- Putting data-fetching logic in instead of
beforeLoad(creates waterfalls,loaderruns sequentially)beforeLoad - Forgetting to pass when creating the router (TypeScript error if using
context)createRootRouteWithContext - Using without
to="."in child components (path resolution may be wrong)from - Not handling the search param in the login page (users lose their intended destination)
redirect
Gotchas and Edge Cases:
- runs sequentially (parent before child) while
beforeLoadruns in parallel - heavy work inloadercreates waterfallsbeforeLoad - The file is auto-generated - never edit it manually, it will be overwritten
routeTree.gen.ts - path string must exactly match the file's location in the routes directory
createFileRoute - Search params are serialized to the URL - avoid large objects, binary data, or sensitive information
- and
notFound()must be thrown, not returnedredirect() - The router plugin must be listed before the React plugin in Vite config
- returns a partial type - only use when you genuinely do not know which route you are on
useSearch({ strict: false }) - Path params () are always strings - cast to number in the loader if needed, not in the component
$postId
</red_flags>
<critical_reminders>
高优先级问题:
- 使用基于文件的路由插件时,手动用定义路由(路由会与生成的树不同步)
createRoute - 直接读取而非
window.location.search(绕过验证,破坏SSR,失去响应性)useSearch() - 在组件渲染时检查鉴权而非使用(组件在重定向前会闪烁,存在竞态条件)
beforeLoad - 布局路由中遗漏(子路由无内容渲染)
<Outlet /> - 在加载器中直接导入服务/客户端而非使用路由上下文(破坏可测试性,耦合到全局状态)
中优先级问题:
- 在加载器中等待非关键数据(不必要地阻塞渲染——对非关键数据使用即发即弃的预取)
- 使用Zod适配器时未使用(无效搜索参数会抛出错误而非回退到默认值)
fallback() - 遗漏注册(Link、navigate失去全应用类型安全)
declare module "@tanstack/react-router" - 在每个路由中重复鉴权检查而非使用无路径布局守卫
- 当外部数据缓存处理新鲜度时使用(每次导航都会重复获取)
staleTime: 0
常见错误:
- 将数据获取逻辑放在而非
beforeLoad中(导致瀑布流,loader顺序执行)beforeLoad - 创建路由时忘记传递(使用
context会触发TypeScript错误)createRootRouteWithContext - 在子组件中使用而未指定
to="."(路径解析可能错误)from - 登录页面未处理搜索参数(用户丢失目标页面)
redirect
陷阱与边缘情况:
- 顺序执行(父路由先于子路由),而
beforeLoad并行执行——loader中的繁重工作会导致瀑布流beforeLoad - 文件自动生成——绝不要手动编辑,会被覆盖
routeTree.gen.ts - 路径字符串必须与文件在routes目录中的位置完全匹配
createFileRoute - 搜索参数会序列化为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,, named constants)import type
(You MUST use for all file-based routes - NEVER define routes manually when using the router plugin)
createFileRoute(You MUST validate search params with - NEVER read raw )
validateSearchwindow.location.search(You MUST use for auth guards and redirects - NEVER check auth inside component render)
beforeLoad(You MUST pass services via router context - NEVER import them directly in loaders (breaks testability))
(You MUST use in layout routes to render child content - forgetting it renders nothing)
<Outlet />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(必须使用验证搜索参数——绝不要直接读取)
validateSearchwindow.location.search(必须使用实现鉴权守卫和重定向——绝不要在组件渲染时检查鉴权)
beforeLoad(必须通过路由上下文传递服务——绝不要在加载器中直接导入服务(会破坏可测试性))
(必须在布局路由中使用渲染子内容——遗漏会导致无内容渲染)
<Outlet />不遵循这些规则会破坏类型安全,在鉴权流程中产生安全漏洞,并导致路由无提示地无法渲染内容。
</critical_reminders>