Tanstack router

From Mindrally/skills · View interactive version

Tanstack router is an AI agent skill from the GitHub repository Mindrally/skills. Type-safe, file-based routing for React with TanStack Router. Use when defining routes with createFileRoute, validating search params with Zod, writing route loaders, setting up auth guards with beforeLoad, integrating TanStack Query into loaders, or configuring router context and preloading.

How to use this skill

Skill file

TanStack Router

TanStack Router is a fully type-safe router for React that treats routes, loaders, params, and search params as first-class typed data rather than untyped strings.

Workflow for Adding a New Route

  1. Create the route file — Add a file under src/routes/ following the file-based routing convention (see below).
  2. Define the route — Export Route from createFileRoute('/path')({...}) with component, and optionally loader, validateSearch, beforeLoad, errorComponent, and pendingComponent.
  3. Validate search params — If the route reads query params, define a Zod schema and pass it as validateSearch.
  4. Load data — Fetch data in loader, not in a component useEffect; integrate with TanStack Query via queryClient.ensureQueryData when caching is needed.
  5. Guard access — Add beforeLoad checks (e.g. auth) that throw redirect({ to: '/login' }) when a precondition fails.
  6. Link to the route — Navigate with <Link to="/path" params={...} search={...}> so the compiler validates params and search at every call site.
  7. Regenerate the route tree — Ensure routeTree.gen.ts is regenerated (automatic under the Vite plugin's dev server / build) before running or building the app.

Core Principles

File-Based Route Conventions

src/routes/
  __root.tsx          ← Root layout
  index.tsx           ← / route
  posts/
    index.tsx         ← /posts
    $postId.tsx       ← /posts/:postId (dynamic segment)
    _layout.tsx       ← Layout route (no path segment)
  _auth/               ← Pathless auth layout group
    dashboard.tsx

Route Definition

export const Route = createFileRoute('/posts/$postId')({
  loader: async ({ params }) => fetchPost(params.postId),
  component: PostComponent,
  errorComponent: ({ error }) => <ErrorBanner message={error.message} />,
  pendingComponent: () => <PostSkeleton />,
})

function PostComponent() {
  const post = Route.useLoaderData()     // type-safe
  const { postId } = Route.useParams()   // type-safe
  return <div>{post.title}</div>
}

Type-Safe Search Params

const searchSchema = z.object({
  page: z.number().int().min(1).default(1),
  q: z.string().optional(),
})

export const Route = createFileRoute('/search')({
  validateSearch: searchSchema,
  component: SearchPage,
})

function SearchPage() {
  const { page, q } = Route.useSearch()
  const navigate = Route.useNavigate()

  return (
    <button onClick={() => navigate({ search: (prev) => ({ ...prev, page: page + 1 }) })}>
      Next page
    </button>
  )
}

Navigation

<Link to="/posts/$postId" params={{ postId: '123' }}>View Post</Link>
<Link to="/search" search={{ page: 1, q: 'react' }}>Search</Link>

Loaders + TanStack Query Integration

export const Route = createFileRoute('/posts')({
  loader: ({ context: { queryClient } }) =>
    queryClient.ensureQueryData(postsQueryOptions()),
  component: PostsPage,
})

function PostsPage() {
  const { data: posts } = useSuspenseQuery(postsQueryOptions())
  return <PostList posts={posts} />
}

Router Context for Dependency Injection

// __root.tsx
interface RouterContext {
  queryClient: QueryClient
  auth: AuthState
}

export const Route = createRootRouteWithContext<RouterContext>()({
  component: RootLayout,
})

// main.tsx
const router = createRouter({ routeTree, context: { queryClient, auth } })

Auth Guards

export const Route = createFileRoute('/_auth/dashboard')({
  beforeLoad: ({ context }) => {
    if (!context.auth.isAuthenticated) throw redirect({ to: '/login' })
  },
  component: Dashboard,
})

Performance

Common Mistakes

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.