tanstack-router
БесплатноБез исполняемых скриптовНе проверен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…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
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 zod
npm install -D @tanstack/router-plugin # Vite plugin: generates the route tree, splits code
// vite.config.ts — the router plugin goes BEFORE the React plugin
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { tanstackRouter } from "@tanstack/router-plugin/vite";
export default defineConfig({
plugins: [
tanstackRouter({ target: "react", autoCodeSplitting: true }),
react(),
],
});
The plugin used to be exported as TanStackRouterVite; that name is deprecated. On first vite dev or vite build it generates src/routeTree.gen.ts from the files in src/routes/. Commit that file or add it to .gitignore consistently, and never edit it.
Create the router once and register it, so every Link, useNavigate and useSearch is typed against your routes:
// src/main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { RouterProvider, createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
const router = createRouter({ routeTree });
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}
createRoot(document.getElementById("root")!).render(
<StrictMode>
<RouterProvider router={router} />
</StrictMode>,
);
File-Based Routing
src/routes/
├── __root.tsx # Root layout (wraps all pages)
├── index.tsx # /
├── about.tsx # /about
├── users/
│ ├── index.tsx # /users
│ └── $userId/
│ ├── route.tsx # layout + loader for /users/:userId (renders <Outlet />)
│ ├── index.tsx # /users/:userId
│ └── posts.tsx # /users/:userId/posts
├── settings/
│ ├── route.tsx # layout wrapper for /settings/*
│ ├── profile.tsx # /settings/profile
│ └── billing.tsx # /settings/billing
└── _auth/ # `_` prefix = pathless layout: adds no URL segment
└── dashboard.tsx # /dashboard
route.tsx inside a directory is the layout for that path. A file such as users/$userId.tsx next to a users/$userId/ directory is also a parent route, so it must render <Outlet /> or its children never show. Dots in a file name are the same as slashes (users.$userId.tsx).
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="/" activeProps={{ className: "font-bold" }}>Home</Link>
<Link to="/users" activeProps={{ className: "font-bold" }}>Users</Link>
<Link to="/about" activeProps={{ className: "font-bold" }}>About</Link>
</nav>
<main className="p-4">
<Outlet />
</main>
</div>
),
});
Link also adds an active class on its own, so Tailwind's [&.active]:font-bold works too.
Route with Search Params and Loader
Zod 4 (current) schemas go straight into validateSearch with no adapter. Use .default(x).catch(x): .default keeps the search params optional on <Link>, .catch replaces malformed URL values instead of showing an error. With only .catch, every <Link to="/users"> has to pass search. Zod 3 needs zodValidator and fallback from @tanstack/zod-adapter.
// src/routes/users/index.tsx
import { createFileRoute, Link } from "@tanstack/react-router";
import { z } from "zod";
type User = { id: string; name: string; email: string };
const usersSearchSchema = z.object({
page: z.number().int().positive().default(1).catch(1),
search: z.string().optional(),
role: z.enum(["all", "admin", "user"]).default("all").catch("all"),
});
export const Route = createFileRoute("/users/")({
validateSearch: usersSearchSchema,
loaderDeps: ({ search }) => ({ page: search.page, search: search.search, role: search.role }),
loader: async ({ deps }) => {
const params = new URLSearchParams({ page: String(deps.page), role: deps.role });
if (deps.search) params.set("search", deps.search);
const res = await fetch(`/api/users?${params}`);
return (await res.json()) as { users: User[]
Установить tanstack-router в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл tanstack-router?
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.
Как установить скилл tanstack-router?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл tanstack-router запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic