TanStack Router

Build type-safe, file-based React routing with TanStack Router. Supports client-side navigation, route loaders, and TanStack Query integration. Use when implementing file-based routing patterns, building SPAs with TypeScript routing, or troubleshooting devtools dependency errors, type safety issues, or Vite bundling problems.

31 stars

Best use case

TanStack Router is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Build type-safe, file-based React routing with TanStack Router. Supports client-side navigation, route loaders, and TanStack Query integration. Use when implementing file-based routing patterns, building SPAs with TypeScript routing, or troubleshooting devtools dependency errors, type safety issues, or Vite bundling problems.

Teams using TanStack Router should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/tanstack-router/SKILL.md --create-dirs "https://raw.githubusercontent.com/ovachiever/droid-tings/main/skills/tanstack-router/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/tanstack-router/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How TanStack Router Compares

Feature / AgentTanStack RouterStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Build type-safe, file-based React routing with TanStack Router. Supports client-side navigation, route loaders, and TanStack Query integration. Use when implementing file-based routing patterns, building SPAs with TypeScript routing, or troubleshooting devtools dependency errors, type safety issues, or Vite bundling problems.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# TanStack Router Skill

Build type-safe, file-based routing for React SPAs with TanStack Router, optimized for Cloudflare Workers deployment.

---

## When to Use This Skill

**Auto-triggers when you mention:**
- "TanStack Router" or "type-safe routing"
- "file-based routing" or "route configuration"
- "React routing" with TypeScript emphasis
- "route loaders" or "data loading in routes"
- "Cloudflare Workers routing"

**Use this skill when:**
- Building SPAs with type-safe navigation
- Implementing file-based routing (like Next.js)
- Need route-level data loading
- Integrating routing with TanStack Query
- Deploying to Cloudflare Workers
- Want better TypeScript support than React Router

---

## Quick Start

### Installation

```bash
npm install @tanstack/react-router @tanstack/router-devtools
npm install -D @tanstack/router-plugin
```

**Latest version:** v1.134.13 (verified 2025-11-07)

### Vite Configuration

```typescript
// 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(), // MUST come before react()
    react(),
  ],
})
```

### Basic Setup

```typescript
// src/routes/__root.tsx
import { createRootRoute, Outlet } from '@tanstack/react-router'

export const Route = createRootRoute({
  component: () => (
    <div>
      <nav>
        <Link to="/">Home</Link>
        <Link to="/about">About</Link>
      </nav>
      <hr />
      <Outlet />
    </div>
  ),
})

// src/routes/index.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/')({
  component: () => <h1>Home Page</h1>,
})

// src/routes/about.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/about')({
  component: () => <h1>About Page</h1>,
})

// src/main.tsx
import { createRouter, RouterProvider } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen' // Auto-generated

const router = createRouter({ routeTree })

function App() {
  return <RouterProvider router={router} />
}
```

---

## Key Features

### 1. Type-Safe Navigation

```typescript
// Fully typed!
<Link to="/posts/$postId" params={{ postId: '123' }} />

// TypeScript error if route doesn't exist
<Link to="/invalid-route" /> // ❌ Error!
```

### 2. Route Loaders (Data Fetching)

```typescript
// src/routes/posts.$postId.tsx
export const Route = createFileRoute('/posts/$postId')({
  loader: async ({ params }) => {
    const post = await fetchPost(params.postId) // Fully typed!
    return { post }
  },
  component: ({ useLoaderData }) => {
    const { post } = useLoaderData()
    return <h1>{post.title}</h1>
  },
})
```

### 3. TanStack Query Integration

```typescript
import { queryOptions } from '@tanstack/react-query'

const postQueryOptions = (postId: string) =>
  queryOptions({
    queryKey: ['posts', postId],
    queryFn: () => fetchPost(postId),
  })

export const Route = createFileRoute('/posts/$postId')({
  loader: ({ context: { queryClient }, params }) =>
    queryClient.ensureQueryData(postQueryOptions(params.postId)),
  component: () => {
    const { postId } = Route.useParams()
    const { data: post } = useQuery(postQueryOptions(postId))
    return <h1>{post.title}</h1>
  },
})
```

---

## Common Errors & Solutions

### Error 1: Devtools Dependency Resolution

**Problem:** Build fails with `@tanstack/router-devtools-core` not found.

**Solution:**
```bash
npm install @tanstack/router-devtools
```

### Error 2: Vite Plugin Order

**Problem:** Routes not auto-generated.

**Solution:** TanStackRouterVite MUST come before react():
```typescript
plugins: [
  TanStackRouterVite(), // First!
  react(),
]
```

### Error 3: Type Registration Missing

**Problem:** `Link to` not typed.

**Solution:**
```typescript
// src/routeTree.gen.ts is auto-generated
// Import it in main.tsx to register types
import { routeTree } from './routeTree.gen'
```

### Error 4: Loader Not Running

**Problem:** Loader function not called on navigation.

**Solution:** Ensure route exports `Route`:
```typescript
export const Route = createFileRoute('/path')({ loader: ... })
```

### Error 5: Memory Leak with Forms

**Problem:** Production crashes when using TanStack Form + Router.

**Solution:** This is a known issue (#5734). Workaround: Use React Hook Form instead, or wait for fix.

---

## Cloudflare Workers Deployment

### Vite Config

```typescript
import { defineConfig } from 'vite'
import { TanStackRouterVite } from '@tanstack/router-plugin/vite'
import { cloudflare } from '@cloudflare/vite-plugin'

export default defineConfig({
  plugins: [
    TanStackRouterVite(),
    react(),
    cloudflare(),
  ],
})
```

### API Backend Pattern

```typescript
// functions/api/posts.ts
export async function onRequestGet({ env }) {
  const { results } = await env.DB.prepare('SELECT * FROM posts').all()
  return Response.json(results)
}

// Client-side route
export const Route = createFileRoute('/posts')({
  loader: async () => {
    const posts = await fetch('/api/posts').then(r => r.json())
    return { posts }
  },
})
```

---

## Templates

All templates in `~/.claude/skills/tanstack-router/templates/`:

1. **package.json** - Dependencies and versions
2. **vite.config.ts** - Vite plugin setup
3. **basic-routes/** - File-based routing structure
4. **route-with-loader.tsx** - Data loading example
5. **query-integration.tsx** - TanStack Query pattern
6. **nested-routes/** - Layout pattern
7. **cloudflare-deployment.md** - Workers setup guide

---

## Reference Docs

Deep-dive guides in `~/.claude/skills/tanstack-router/references/`:

1. **file-based-routing.md** - Route structure conventions
2. **type-safety.md** - TypeScript patterns
3. **data-loading.md** - Loaders and TanStack Query
4. **cloudflare-workers.md** - Deployment guide
5. **common-errors.md** - All 7+ errors with solutions
6. **migration-guide.md** - From React Router

---

## Integration with Existing Skills

**Works with:**
- **tanstack-query** - Recommended for data fetching
- **tanstack-table** - Display data from routes
- **cloudflare-worker-base** - API backend
- **tailwind-v4-shadcn** - UI styling

---

## Token Efficiency

**Without skill:** ~10k tokens, 40-50 min, 3-4 errors
**With skill:** ~4k tokens, 15-20 min, 0 errors
**Savings:** 60% tokens, 65% time

---

## Production Validation

**Tested with:**
- React 19.2, Vite 6.0, TypeScript 5.8
- Cloudflare Workers (Wrangler 4.0)
- TanStack Query v5.90.7

**Stack compatibility:**
- ✅ Cloudflare Workers + Static Assets
- ✅ TanStack Query integration
- ✅ TypeScript strict mode

---

**Last Updated:** 2025-11-07
**Library Version:** @tanstack/react-router v1.134.13

Related Skills

TanStack Table

31
from ovachiever/droid-tings

Build headless data tables with TanStack Table v8. Provides server-side pagination, filtering, sorting, and virtualization patterns for Cloudflare Workers + D1 databases. Use when building tables with large datasets, coordinating with TanStack Query, or troubleshooting state management issues, pagination coordination errors, or performance bottlenecks.

TanStack Start

31
from ovachiever/droid-tings

Build full-stack React applications with TanStack Start on Cloudflare Workers. Type-safe routing, server functions, SSR/streaming, and seamless D1/KV/R2 integration. Use when: building full-stack React apps, need SSR with Cloudflare Workers, want type-safe server functions, or migrating from Next.js. RC status - v1.0 stable pending. Monitor tanstack/router#5734 (memory leak) before production use.

tanstack-query

31
from ovachiever/droid-tings

Manage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.

zustand-state-management

31
from ovachiever/droid-tings

Build type-safe global state in React applications with Zustand. Supports TypeScript, persist middleware, devtools, slices pattern, and Next.js SSR. Use when setting up React state, migrating from Redux/Context API, implementing localStorage persistence, or troubleshooting Next.js hydration errors, TypeScript inference issues, or infinite render loops.

zinc-database

31
from ovachiever/droid-tings

Access ZINC (230M+ purchasable compounds). Search by ZINC ID/SMILES, similarity searches, 3D-ready structures for docking, analog discovery, for virtual screening and drug discovery.

zarr-python

31
from ovachiever/droid-tings

Chunked N-D arrays for cloud storage. Compressed arrays, parallel I/O, S3/GCS integration, NumPy/Dask/Xarray compatible, for large-scale scientific computing pipelines.

youtube-transcript

31
from ovachiever/droid-tings

Download YouTube video transcripts when user provides a YouTube URL or asks to download/get/fetch a transcript from YouTube. Also use when user wants to transcribe or get captions/subtitles from a YouTube video.

xlsx

31
from ovachiever/droid-tings

Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas

wordpress-plugin-core

31
from ovachiever/droid-tings

Build secure WordPress plugins with core patterns for hooks, database interactions, Settings API, custom post types, REST API, and AJAX. Covers three architecture patterns (Simple, OOP, PSR-4) and the Security Trinity. Use when creating plugins, implementing nonces/sanitization/escaping, working with $wpdb prepared statements, or troubleshooting SQL injection, XSS, CSRF vulnerabilities, or plugin activation errors.

whisper

31
from ovachiever/droid-tings

OpenAI's general-purpose speech recognition model. Supports 99 languages, transcription, translation to English, and language identification. Six model sizes from tiny (39M params) to large (1550M params). Use for speech-to-text, podcast transcription, or multilingual audio processing. Best for robust, multilingual ASR.

weights-and-biases

31
from ovachiever/droid-tings

Track ML experiments with automatic logging, visualize training in real-time, optimize hyperparameters with sweeps, and manage model registry with W&B - collaborative MLOps platform

webapp-testing

31
from ovachiever/droid-tings

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.