Skip to content
Skills Library
Programming · Building & coding

tanstack-router

/tanstack-router

TanStack Router for React with file-based routing. Covers route definitions, layouts, authentication guards, loaders, and type-safe navigation. USE WHEN: user mentions "TanStack Router", "file-based routing", "type-safe routing", "route loaders", "beforeLoad", asks about "TanStack Router patterns", "typed navigation" DO NOT USE FOR: React Router v6 - use React Router docs, Next.js App Router - use `react-server-components`, Vue Router, Angular Router

Licence
MIT
Last repository change
21.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 21.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

TanStack Router for React with file-based routing. Covers route definitions, layouts, authentication guards, loaders, and type-safe navigation. USE WHEN: user mentions "TanStack Router", "file-based routing", "type-safe routing", "route loaders", "beforeLoad", asks about "TanStack Router patterns", "typed navigation" DO NOT USE FOR: React Router v6 - use React Router docs, Next.js App Router - use `react-server-components`, Vue Router, Angular Router

Triggers from the description

TanStack Routerfile-based routingtype-safe routingroute loadersbeforeLoadTanStack Router patternstyped navigation
Original author description

TanStack Router for React with file-based routing. Covers route definitions, layouts, authentication guards, loaders, and type-safe navigation. USE WHEN: user mentions "TanStack Router", "file-based routing", "type-safe routing", "route loaders", "beforeLoad", asks about "TanStack Router patterns", "typed navigation" DO NOT USE FOR: React Router v6 - use React Router docs, Next.js App Router - use `react-server-components`, Vue Router, Angular Router

How it works

  1. When NOT to Use This Skill
  2. File-Based Route Structure
  3. Root Route
  4. Auth Guard Layout
  5. Protected Route with Loader
  6. Dynamic Route with Params
  7. Navigation
  8. Search Params with Validation
  9. Router Configuration
  10. Key Concepts
Original SKILL.md headings · 236 lines, 813 words
SKILL.md preview
---
name: tanstack-router
description: |
  TanStack Router for React with file-based routing. Covers route definitions,
  layouts, authentication guards, loaders, and type-safe navigation.

  USE WHEN: user mentions "TanStack Router", "file-based routing", "type-safe routing",
  "route loaders", "beforeLoad", asks about "TanStack Router patterns", "typed navigation"

  DO NOT USE FOR: React Router v6 - use React Router docs,
  Next.js App Router - use `react-server-components`, Vue Router, Angular Router
allowed-tools: Read, Grep, Glob, Write, Edit
---
# TanStack Router Patterns

> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `tanstack-router` for comprehensive documentation.

## When NOT to Use This Skill

Skip this skill when:
- Using React Router v6 (different API)
- Building Next.js apps with App Router (use RSC patterns)
- Working with Vue Router (use Vue-specific routing)
- Using Angular Router (use Angular routing)
- Client-side routing not needed (static sites)

## File-Based Route Structure

```
src/routes/
├── __root.tsx           # Root layout
├── _authenticated.tsx   # Auth guard layout
├── _authenticated/
│   ├── dashboard.tsx    # /dashboard
│   └── users/
│       ├── index.tsx    # /users
│       └── $userId.tsx  # /users/:userId
├── login.tsx            # /login
└── register.tsx         # /register
```

## Root Route

```tsx
// routes/__root.tsx
import { createRootRoute, Outlet } from '@tanstack/react-router';
import { QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from 'sonner';
import { queryClient } from '@/lib/query-client';

export const Route = createRootRoute({
  component: RootComponent,
});

function RootComponent() {
  return (
    <QueryClientProvider client={queryClient}>
      <Outlet />
      <Toaster richColors position="top-right" />
    </QueryClientProvider>
  );
}
```

## Auth Guard Layout

```tsx
// routes/_authenticated.tsx
import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';
import { useAuthStore } from '@/stores/authStore';
import { MainLayout } from '@/layouts/MainLayout';

export const Route = createFileRoute('/_authenticated')({
  beforeLoad: ({ location }) => {
    const isAuthenticated = useAuthStore.getState().isAuthenticated;
    if (!isAuthenticated) {
      throw redirect({
        to: '/login',
        search: { redirect: location.href },
      });
    }
  },
  component: AuthenticatedLayout,
});

function AuthenticatedLayout() {
  return (
    <MainLayout>
      <Outlet />
    </MainLayout>
  );
}
```

## Protected Route with Loader

```tsx
// routes/_authenticated/users/index.tsx
import { createFileRoute } from '@tanstack/react-router';
import { usersApi } from '@/api/users.api';
import { UserList } from '@/features/users/components/UserList';

export const Route = createFileRoute('/_authenticated/users/')({
  loader: async () => {
    return usersApi.getAll();
  },
  component: UsersPage,
});

function UsersPage() {
  const users = Route.useLoaderData();
  return <UserList users={users} />;
}
```

## Dynamic Route with Params

```tsx
// routes/_authenticated/users/$userId.tsx
import { createFileRoute, notFound } from '@tanstack/react-router';
import { usersApi } from '@/api/users.api';
import { UserDetail } from '@/features/users/components/UserDetail';

export const Route = createFileRoute('/_authenticated/users/$userId')({
  loader: async ({ params }) => {
    const user = await usersApi.getById(params.userId);
    if (!user) throw notFound();
    return user;
  },
  component: UserDetailPage,
  notFoundComponent: () => <div>User not found</div>,
});

function UserDetailPage() {
  const user = Route.useLoaderData();
  return <UserDetail user={user} />;
}
```

## Navigation

```tsx
import { Link, useNavigate, useRouter } from '@tanstack/react-router';

// Declarative navigation
<Link to="/users/$userId" params={{ userId: '123' }}>
  View User
</Link>

// Programmatic navigation
const navigate = useNavigate();
navigate({ to: '/dashboard' });
navigate({ to: '/users/$userId', params: { userId: '123' } });

// With search params
navigate({
  to: '/users',
  search: { page: 1, sort: 'name' },
});

// Go back
const router = useRouter();
router.history.back();
```

## Search Params with Validation

```tsx
import { createFileRoute } from '@tanstack/react-router';
import { z } from 'zod';

const searchSchema = z.object({
  page: z.number().default(1),
  search: z.string().optional(),
  sort: z.enum(['name', 'email', 'createdAt']).default('createdAt'),
});

export const Route = createFileRoute('/_authenticated/users/')({
  validateSearch: searchSchema,
  component: UsersPage,
});

function UsersPage() {
  const { page, search, sort } = Route.useSearch();
  // Type-safe search params
}
```

## Router Configuration

```tsx
// router.ts
import { createRouter } from '@tanstack/react-router';
import { routeTree } from './routeTree.gen';

export const router = createRouter({
  routeTree,
  defaultPreload: 'intent',
  defaultPreloadStaleTime: 0,
});

declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router;
  }
}
```

## Key Concepts

| Concept | Description |
|---------|-------------|
| `__root.tsx` | Global layout, providers |
| `_layout.tsx` | Route group layout |
| `$param.tsx` | Dynamic route segment |
| `index.tsx` | Index route |
| `beforeLoad` | Pre-navigation guard |
| `loader` | Data fetching |
| `notFound` | 404 handling |

## Anti-Patterns

| Anti-Pattern | Why It's Bad | Correct Approach |
|--------------|--------------|------------------|
| Fetching in components | Not type-safe, duplicate requests | Use route loaders |
| Not using search param validation | Runtime errors | Use Zod schema validation |
| Hardcoded navigation paths | Type-unsafe, breaks on refactor | Use typed `Link` and `navigate` |
| Mixing React Router patterns | Different API | Use TanStack Router idioms |
| Not using `beforeLoad` for auth | Auth check in component | Use `beforeLoad` hook |
| Large route files | Hard to maintain | Split into feature modules |

## Quick Troubleshooting

| Issue | Likely Cause | Solution |
|-------|--------------|----------|
| Type error on navigation | Wrong route path | Use autocomplete from `to` prop |
| Loader not running | Missing loader in route | Add loader to route definition |
| Redirect not working | Wrong redirect syntax | Use `throw redirect({ to: '...' })` |
| Search params not updating | Not using `useSearch` | Use `Route.useSearch()` |
| Route not found | File naming wrong | Check file-based routing convention |
| Auth guard not firing | Not in `beforeLoad` | Move auth check to `beforeLoad` |

## Reference Documentation

> **Deep Knowledge**: Use `mcp__documentation__fetch_docs` with technology: `tanstack-router` for comprehensive documentation.

- [File-based Routing](quick-ref/routing.md)
- [Auth Guards](quick-ref/guards.md)

Versions

RepositoryScoreLicence
This page · claude-dev-suite/claude-dev-suite100MIT
TerminalSkills/skills100Apache-2.0
Mindrally/skills100Apache-2.0
secondsky/claude-skills100MIT

Database snapshot: 13.11.2026 · package version 56e6f17ca495 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100react-tanstack-router
    Use when implementing routing in a React app (NOT Next.js) with TanStack Router — file-based routes, loaders, search params.
  • 90TanStack Router
    Expert guidance for TanStack Router including file-based routing, type-safe navigation, route loaders, search params, nested routes, and lazy loading. Use this when building type-safe React applications with client-side routing.
  • 100tanstack
    Type-safe React with TanStack Query (fetching, caching, mutations), Router (file-based routing, search params, loaders), and Start (SSR, server functions). Use for react-query, server state, typed search params, route loaders, or SSR.
  • 100set-up-routing
    Use when adding client-side routing to a frontend SPA — wires TanStack Router (typed, file-based, React) or Vue Router (Vue) with lazy route code-splitting, loaders that prefetch into the TanStack Query cache, per-route error + pending UI, and a guard pattern for protected routes.
  • 95tanstack-router-best-practices
    TanStack Router best practices for type-safe routing, data loading, search params, and navigation. Activate when building React applications with complex routing needs.
  • 95tanstack-start
    Build JSON-defined TanStack Start applications with @json-render/tanstack-start. Use for Start route specs, splat routing, SSR loaders, head metadata, layouts, and client navigation. Do not use for generic TanStack Router apps that do not use json-render.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.