tanstack-router
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "tanstack-router" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-bdeabe2780eef25ee35fa5b3fb7aa50a9791e0a1bd41c06d8e54935f42708581. Verify the upstream source and version against https://github.com/TerminalSkills/skills before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
github.com
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
A type-safe routing solution for React that supports file-based routing, Zod-validated search params, route loaders, and automatic code-splitting. Suited for situations like “set up routing for React,” “type-safe router,” “TanStack Router,” file-based routing, search param validation, replacing React Router with a typed approach, or adding route-level data loading.
Introduction source: third_party · TerminalSkills · 1.0.0 Reference
SkillPi interpretation
- Audience
- React SPA or SSR app that needs type-safe routing (links, params, search) Migrating from React Router and want compile-time route safety Need validated and typed search/query params (not just `string | undefined`) Route-level data loading with pending/error states File-based routing with automatic code splitting
- Testing
- Not tested
Browse files
Frontmatter
name: tanstack-router
description: >-
Type-safe routing for React with file-based routes, validated search params,
loaders, and automatic code splitting. Use when someone asks to "set up
routing for React", "type-safe router", "TanStack Router", "file-based
routing", "search params validation", "replace React Router with something
type-safe", or "add route-level data loading". Covers file-based routing,
search params with Zod, route loaders, code splitting, and layouts.
license: Apache-2.0
compatibility: "React 18+. TypeScript recommended."
metadata:
author: terminal-skills
version: "1.0.0"
category: development
tags: ["react", "routing", "typescript", "tanstack", "file-based-routes"]TanStack Router
Overview
TanStack Router is a fully type-safe router for React. Every route path, search param, path param, and loader is typed end-to-end — if you change a route, TypeScript catches every broken link at compile time. File-based routing with automatic code splitting, validated search params, and route-level data loading.
When to Use
- React SPA or SSR app that needs type-safe routing (links, params, search)
- Migrating from React Router and want compile-time route safety
- Need validated and typed search/query params (not just
string | undefined) - Route-level data loading with pending/error states
- File-based routing with automatic code splitting
Instructions
Setup
npm install @tanstack/react-router
npm install -D @tanstack/router-plugin # Vite plugin for file-based routing
// vite.config.ts
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { TanStackRouterVite } from "@tanstack/router-plugin/vite";
export default defineConfig({
plugins: [TanStackRouterVite(), react()],
});
File-Based Routing
src/routes/
├── __root.tsx # Root layout (wraps all pages)
├── index.tsx # /
├── about.tsx # /about
├── users/
│ ├── index.tsx # /users
│ ├── $userId.tsx # /users/:userId (dynamic param)
│ └── $userId/
│ └── posts.tsx # /users/:userId/posts (nested)
└── settings/
├── _layout.tsx # Layout wrapper for /settings/*
├── profile.tsx # /settings/profile
└── billing.tsx # /settings/billing
Root Layout
// src/routes/__root.tsx
import { createRootRoute, Outlet, Link } from "@tanstack/react-router";
export const Route = createRootRoute({
component: () => (
<div>
<nav className="flex gap-4 p-4 border-b">
<Link to="/" className="[&.active]:font-bold">Home</Link>
<Link to="/users" className="[&.active]:font-bold">Users</Link>
<Link to="/about" className="[&.active]:font-bold">About</Link>
</nav>
<main className="p-4">
<Outlet />
</main>
</div>
),
});
Route with Loader
// src/routes/users/index.tsx — Route with data loading
import { createFileRoute } from "@tanstack/react-router";
import { z } from "zod";
// Search params schema — validated and typed
const usersSearchSchema = z.object({
page: z.number().int().positive().catch(1),
search: z.string().optional(),
role: z.enum(["all", "admin", "user"]).catch("all"),
});
export const Route = createFileRoute("/users/")({
// Validate search params with Zod
validateSearch: usersSearchSchema,
// Load data before rendering (with typed search params)
loaderDeps: ({ search }) => ({ search }),
loader: async ({ deps: { search } }) => {
const params = new URLSearchParams({
page: String(search.page),
...(search.search && { search: search.search }),
...(search.role !== "all" && { role: search.role }),
});
const res = await fetch(`/api/users?${params}`);
return res.json() as Promise<{ users: User[]; total: number }>;
},
component: UsersPage,
});
function UsersPage() {
const { users, total } = Route.useLoaderData();
const { page, search, role } = Route.useSearch();
const navigate = Route.useNavigate();
return (
<div>
<h1>Users ({total})</h1>
<input
value={search ?? ""}
onChange={(e) => navigate({ search: { search: e.target.value, page: 1 } })}
placeholder="Search users..."
/>
<select
value={role}
onChange={(e) => navigate({ search: { role: e.target.value as any, page: 1 } })}
>
<option value="all">All roles</option>
<option value="admin">Admin</option>
<option value="user">User</option>
</select>
{users.map((user) => (
<Link key={user.id} to="/users/$userId" params={{ userId: user.id }}>
{user.name}
</Link>
))}
<button
disabled={page <= 1}
onClick={() => navigate({ search: { page: page - 1 } })}
>
Previous
</button>
<button onClick={() => navigate({ search: { page: page + 1 } })}>
Next
</button>
</div>
);
}
Dynamic Route Params
// src/routes/users/$userId.tsx — Dynamic route with typed params
import { createFileRoute, notFound } from "@tanstack/react-router";
export const Route = createFileRoute("/users/$userId")({
loader: async ({ params: { userId } }) => {
// userId is typed as string — no casting needed
const res = await fetch(`/api/users/${userId}`);
if (!res.ok) throw notFound();
return res.json() as Promise<User>;
},
notFoundComponent: () => <div>User not found</div>,
component: UserProfile,
});
function UserProfile() {
const user = Route.useLoaderData();
// ^? User — fully typed from loader return
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
<Link to="/users/$userId/posts" params={{ userId: user.id }}>
View Posts
</Link>
</div>
);
}
Type-Safe Links
// Links are fully typed — wrong routes or missing params = compile error
import { Link } from "@tanstack/react-router";
// ✅ Correct — route exists, params match
<Link to="/users/$userId" params={{ userId: "123" }}>Profile</Link>
// ✅ Search params typed
<Link to="/users" search={{ page: 2, role: "admin" }}>Admin Users</Link>
// ❌ Compile error — route doesn't exist
<Link to="/nonexistent">Broken</Link>
// ❌ Compile error — missing required param
<Link to="/users/$userId">Missing userId</Link>
Examples
Example 1: Dashboard with filtered data views
User prompt: "Build a dashboard with users list that supports search, pagination, and role filtering — all in the URL."
The agent will set up TanStack Router with validated search params (page, search, role), route-level loader that fetches filtered data, and type-safe navigation that preserves filter state in the URL.
Example 2: Nested layouts for settings
User prompt: "Create a settings page with sidebar navigation — profile, billing, and team sections."
The agent will create a settings layout route with sidebar Links, nested routes for each section, and loaders for settings data.
Guidelines
- Search params = state — use URL search params instead of React state for filterable/bookmarkable views
- Validate search params with Zod —
.catch()provides defaults for invalid params - Loaders run before render — no loading spinners for route-level data
notFound()in loaders — throw it to render the notFoundComponent- Links are type-checked — changing a route path catches all broken links at compile time
- File naming = route structure —
$paramfor dynamic segments,_layoutfor layout routes - Code splitting is automatic — each route file becomes a separate chunk
loaderDepscontrols re-fetching — loader re-runs only when deps change- TanStack Router + TanStack Query — use together for server state + route state
Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- TanStack Router 提供端到端类型安全的 React 路由解决方案,显著提升开发效率与代码可靠性
- 涵盖文件路由、搜索参数验证、数据加载等高频刚需场景,适用于 React 项目迁移或新建
Highlights
- 触发词覆盖全面,包括“类型安全路由器”、“基于文件的路由”、“搜索参数验证”等关键变体
- 边界清晰,能有效区分于其他路由方案,减少误触或漏触
Highlights
- 文档结构完整,从概述、使用场景到详细实现步骤逻辑清晰
- 提供多个端到端示例(如用户列表、设置页布局),frontmatter 信息齐全
Highlights
- 依赖包来源明确,版本兼容说明清晰(React 18+,TypeScript 推荐)
- 涵盖异常处理机制(如 notFound()、loaderDeps 控制),确保执行稳定性
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
-
Install or fetch external dependencies
Use official sources and pin versions. Check install scripts in an isolated environment. This document check does not cover code downloaded later.
Mentioned in main document · lines 38, 39
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.