mcpField
R
react-tanstack-router

react-tanstack-router

github.com/fusengineDevelopment3440 installsUpdated 2w ago
Repository

About react-tanstack-router

A TanStack Router skill for React single-page applications, covering file-based, type-safe routing and data loading with TanStack Query. It includes patterns and templates for search validation, nested layouts, protected routes, and React Router migration; it is not for Next.js.

Key features

  1. 01File-based, type-safe routing
  2. 02Zod and Valibot search validation
  3. 03Loaders integrated with TanStack Query
  4. 04Nested layouts and route context
  5. 05Protected routes and preloading
  6. 06React Router migration guidance

Use cases

  1. 01Structuring routes in a React SPA
  2. 02Validating URL filters and pagination
  3. 03Loading route data with TanStack Query
  4. 04Adding authenticated routes and dashboard layouts

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/fusengine/agents --skill react-tanstack-router

After installing, type/react-tanstack-routerin Claude Code to confirm it loaded.

Bundled files

References and scripts installed along with SKILL.md.

references/
auth-guards.md
code-splitting.md
components.md
devtools.md
error-handling.md
file-based-routing.md
hooks.md
installation.md
loaders.md
navigation.md
nested-routes.md
preloading.md
route-context.md
route-params.md
search-params.md
ssr.md
tanstack-query.md
typescript.md
references/templates/
auth-protected-routes.md
basic-setup.md
dashboard-layout.md
feature-module.md
search-filters.md

Details

From the project README
Implements TanStack Router for React SPAs (Vite/Webpack/Rspack, not Next.js): file-based routing with auto-generated type safety, dynamic route params (`$postId`), search-params validation with Zod/Valibot, loaders (`Route.useLoaderData()`) integrated with TanStack Query (`ensureQueryData`), nested layouts with `Outlet`, route context for dependency injection, protected routes via `beforeLoad` guards, and preloading on intent/render.

Covers the full SOLID module structure (modules/cores/lib/router/, feature modules with interfaces//queries//components/), migration from React Router (useParams()→Route.useParams(), loader→loader option), and error boundaries/404 handling. Does not cover state management (react-state) or forms (react-forms) — those are separate skills; for Next.js routing use the App Router (nextjs-16), not this skill.

TanStack Router

100% type-safe router for React with file-based routing, loaders, search params validation, and deep TanStack Query integration.

Agent Workflow (MANDATORY)

Before ANY implementation, spawn 3 agents in parallel, one Agent call each with a name:

  1. fuse-ai-pilot:explore-codebase - Analyze existing routes and navigation patterns
  2. fuse-ai-pilot:research-expert - Verify latest TanStack Router docs via Context7/Exa
  3. mcp__context7__query-docs - Check file-based routing and type-safe patterns

After implementation, run fuse-ai-pilot:sniper for validation.


Overview

Why TanStack Router?

TanStack Router is the recommended choice for React SPAs requiring type-safe routing with search params validation.

FeatureTanStack RouterReact Router v7
Type SafetyFull inferenceAuto-generated
File-based RoutingBuilt-inFramework mode
Search Params ValidationZod, ValibotManual
PreloadingIntent, renderLimited
TanStack Query IntegrationNativeManual
When to Use

Critical Rules

  1. ALWAYS use file-based routing - Auto-generated type safety → file-based-routing.md
  2. ALWAYS validate search params - Pass the Zod v4 schema directly to validateSearch (zodValidator only for Zod v3) → search-params.md
  3. ALWAYS use Route.useLoaderData() - Not global useLoaderData → hooks.md
  4. ALWAYS register router types - declare module '@tanstack/react-router' → typescript.md
  5. PREFER loaders over useEffect - Data fetching before render → loaders.md
  6. INTEGRATE TanStack Query - For caching, mutations, optimistic updates → tanstack-query.md
  7. FOLLOW SOLID architecture - Modules, interfaces, file size limits → solid-react skill

Quick Reference: What to Read

Starting a new project
  1. Read installation.md for configuration
  2. Copy template basic-setup.md as base
Creating a feature module (posts, users, etc.)
  1. Follow architecture in templates/feature-module.md
  2. Use patterns from tanstack-query.md for queries
Implementing authentication
  1. Read auth-guards.md for concepts
  2. Copy template auth-protected-routes.md
Creating a page with filters/search
  1. Read search-params.md for Zod validation
  2. Copy template search-filters.md
Creating a dashboard with nested layouts
  1. Read nested-routes.md for concepts
  2. Copy template dashboard-layout.md

Project Structure (SOLID Architecture)

Recommended structure following SOLID principles from solid-react skill.

src/
├── modules/
│   ├── cores/                      # Shared between features
│   │   ├── lib/
│   │   │   ├── router/router.ts    # Router configuration
│   │   │   └── query/client.ts     # QueryClient configuration
│   │   ├── components/layouts/     # Shared layouts
│   │   └── interfaces/             # Shared types
│   └── [feature]/                  # Feature module
│       ├── src/
│       │   ├── interfaces/         # Module types
│       │   ├── queries/            # TanStack Query options
│       │   └── components/         # Module components
│       └── index.ts                # Public exports
├── routes/                         # Route definitions ONLY
│   ├── __root.tsx
│   └── [feature]/
└── routeTree.gen.ts               # Auto-generated (DO NOT MODIFY)

Full template: templates/basic-setup.md


Reference Guide

Concepts (references/) - Conceptual Documentation
TopicReferenceWhen to consult
Setupinstallation.mdVite/Webpack config, React Router migration
File Routingfile-based-routing.mdNaming conventions, routes/ structure
URL Paramsroute-params.mdDynamic routes $postId, parsing
Search Paramssearch-params.mdZod validation, URL filters, pagination
Data Loadingloaders.mdLoaders, prefetch, TanStack Query integration
Navigationnavigation.mdLink, useNavigate, redirects
Contextroute-context.mdDependency injection, QueryClient, user
Layoutsnested-routes.mdNested layouts, Outlet, pathless routes
Errorserror-handling.mdError boundaries, 404, pending states
Lazy Loadingcode-splitting.mdCode splitting, bundle optimization
Preloadingpreloading.mdPreload intent/render, prefetch
Authauth-guards.mdProtected routes, RBAC, login redirect
TanStack Querytanstack-query.mdqueryOptions, mutations, cache
SSRssr.mdServer-side rendering, TanStack Start
TypeScripttypescript.mdType registration, inference, type safety
DevToolsdevtools.mdRouter DevTools setup
Hooks APIhooks.mduseParams, useSearch, useNavigate, etc.
Componentscomponents.mdLink, Outlet, Navigate, RouterProvider
Templates (references/templates/) - Complete Copy-Paste Ready Code
TemplateWhen to use
basic-setup.mdStart a new project with SOLID architecture
feature-module.mdCreate a complete feature module (interfaces, queries, components)
auth-protected-routes.mdImplement login, protected routes, RBAC
search-filters.mdPage with URL filters, pagination, sorting
dashboard-layout.mdDashboard with sidebar, tabs, nested layouts

Core Patterns

1. Root Route with Context

Router context configuration for dependency injection.

// src/routes/__root.tsx
export const Route = createRootRouteWithContext<RouterContext>()({
  component: RootComponent,
})

Details: route-context.md Template: templates/basic-setup.md

2. File Route with Loader and TanStack Query

Recommended pattern for data loading with cache.

// src/routes/posts/$postId.tsx
export const Route = createFileRoute('/posts/$postId')({
  loader: ({ context: { queryClient }, params }) =>
    queryClient.ensureQueryData(postQueryOptions(params.postId)),
  component: PostPage,
})

Details: loaders.md, tanstack-query.md Template: templates/feature-module.md

3. Search Params with Zod Validation

Type-safe filters and pagination via URL.

// src/routes/posts/index.tsx
const searchSchema = z.object({
  page: z.number().min(1).default(1),
  sort: z.enum(['newest', 'oldest']).default('newest'),
})

export const Route = createFileRoute('/posts/')({
  validateSearch: searchSchema, // Zod v4 = Standard Schema, no adapter
})

Details: search-params.md Template: templates/search-filters.md

4. Protected Routes

Authentication guard with redirect.

// src/routes/_authenticated/_authenticated.tsx
export const Route = createFileRoute('/_authenticated')({
  beforeLoad: ({ context, location }) => {
    if (!context.user) {
      throw redirect({ to: '/login', search: { redirect: location.href } })
    }
  },
})

Details: auth-guards.md Template: templates/auth-protected-routes.md

5. Nested Layouts with Outlet

Nested layouts for dashboards.

// src/routes/_dashboard/_dashboard.tsx
export const Route = createFileRoute('/_dashboard')({
  component: () => (
    <DashboardLayout>
      <Outlet />
    </DashboardLayout>
  ),
})

Details: nested-routes.md Template: templates/dashboard-layout.md


Best Practices

Do's
PatternReference
Use Route API (Route.useParams())hooks.md
Validate search params with Zodsearch-params.md
Use ensureQueryData in loaderstanstack-query.md
Preload on intent for linkspreloading.md
Separate interfaces in interfaces/solid-react skill
Don'ts
Anti-patternWhyAlternative
useLoaderData() without fromNot type-safeRoute.useLoaderData()
useEffect for fetchNot optimalUse loaders
Mutate search paramsImmutabilitynavigate({ search: {...} })
Skip error boundariesDegraded UXAdd errorComponent
Interfaces in componentsCouplinginterfaces/ folder

Migration from React Router

See installation.md for complete migration guide.

React RouterTanStack Router
useParams()Route.useParams()
useSearchParams()Route.useSearch()
useLoaderData()Route.useLoaderData()
loader functionloader option
action functionTanStack Query mutations

Version History

  • v1.x - Frequent releases (incremental versioning)
  • Key milestones: Head/meta tags, Search params middlewares, Zod adapter

Comments

Markdown supported