> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/tanstack/router/llms.txt
> Use this file to discover all available pages before exploring further.

# File-based routing

> Set up automatic route generation from your file system structure

File-based routing automatically generates your route tree from your file system structure, eliminating the need to manually define routes in code.

## Overview

With file-based routing, you create route files in a designated directory (typically `src/routes/`), and TanStack Router automatically generates the route configuration for you. This provides:

* **Zero configuration** - Routes are automatically discovered
* **Type safety** - Full TypeScript support with generated types
* **Code splitting** - Automatic code splitting per route
* **Colocation** - Keep route logic close to the route definition

## Setup

<Steps>
  <Step title="Install the plugin">
    Install the Vite plugin (or your bundler's equivalent):

    <CodeGroup>
      ```bash npm theme={null}
      npm install -D @tanstack/router-plugin
      ```

      ```bash yarn theme={null}
      yarn add -D @tanstack/router-plugin
      ```

      ```bash pnpm theme={null}
      pnpm add -D @tanstack/router-plugin
      ```
    </CodeGroup>
  </Step>

  <Step title="Configure the plugin">
    Add the plugin to your Vite config:

    ```typescript vite.config.ts theme={null}
    import { defineConfig } from 'vite'
    import react from '@vitejs/plugin-react'
    import { TanStackRouterVite } from '@tanstack/router-plugin/vite'

    export default defineConfig({
      plugins: [TanStackRouterVite(), react()],
    })
    ```
  </Step>

  <Step title="Create your route files">
    Create route files in `src/routes/` using the `createFileRoute` function:

    ```tsx src/routes/__root.tsx theme={null}
    import { createRootRoute, Outlet } from '@tanstack/react-router'
    import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'

    export const Route = createRootRoute({
      component: () => (
        <>
          <Outlet />
          <TanStackRouterDevtools />
        </>
      ),
    })
    ```

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

    export const Route = createFileRoute('/')({
      component: () => <div>Welcome Home!</div>,
    })
    ```
  </Step>
</Steps>

## File naming conventions

### Standard routes

```
src/routes/
  __root.tsx       -> /
  index.tsx        -> /
  about.tsx        -> /about
  posts.tsx        -> /posts
  posts/index.tsx  -> /posts
  posts/$id.tsx    -> /posts/:id
```

### Dynamic parameters

Use `$` prefix for path parameters:

```
posts/$postId.tsx           -> /posts/:postId
users/$userId/edit.tsx      -> /users/:userId/edit
```

### Pathless routes

Use `_` prefix for layout routes without adding to the path:

```
_layout.tsx                 -> Wraps children but doesn't add to URL
_layout/dashboard.tsx       -> /dashboard (with _layout wrapper)
```

### Route groups

Use parentheses for organizational grouping:

```
(auth)/login.tsx            -> /login
(auth)/register.tsx         -> /register
```

## Route options

Define route behavior using the route object:

```tsx src/routes/posts/$postId.tsx theme={null}
import { createFileRoute } from '@tanstack/react-router'
import { fetchPost } from '@/api'

export const Route = createFileRoute('/posts/$postId')({
  // Load data before rendering
  loader: async ({ params }) => {
    return await fetchPost(params.postId)
  },
  // Main component
  component: PostComponent,
  // Error boundary
  errorComponent: ({ error }) => <div>Error: {error.message}</div>,
  // Pending component
  pendingComponent: () => <div>Loading post...</div>,
})

function PostComponent() {
  const { postId } = Route.useParams()
  const post = Route.useLoaderData()
  
  return (
    <article>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </article>
  )
}
```

## Code splitting

Separate route code from component code for better performance:

```tsx src/routes/posts/$postId.tsx theme={null}
import { createFileRoute } from '@tanstack/react-router'
import { fetchPost } from '@/api'

export const Route = createFileRoute('/posts/$postId')({
  loader: async ({ params }) => await fetchPost(params.postId),
}).lazy(() => import('./posts.$postId.lazy'))
```

```tsx src/routes/posts/$postId.lazy.tsx theme={null}
import { createLazyFileRoute } from '@tanstack/react-router'

export const Route = createLazyFileRoute('/posts/$postId')({
  component: PostComponent,
})

function PostComponent() {
  const post = Route.useLoaderData()
  return <article>{post.title}</article>
}
```

## Type generation

The plugin automatically generates type-safe route definitions:

```typescript src/routeTree.gen.ts theme={null}
// This file is auto-generated by TanStack Router
import type { RootRoute } from './routes/__root'
import type { IndexRoute } from './routes/index'

export interface FileRouteTypes {
  '/': {
    component: typeof IndexRoute
  }
}
```

<Note>
  Commit the generated `routeTree.gen.ts` file to version control to enable type checking in CI/CD.
</Note>

## Best practices

<Accordion title="Keep route files focused">
  Route files should contain route configuration and data loading logic. Move complex components to separate files.
</Accordion>

<Accordion title="Use lazy loading for large components">
  Split heavy components into `.lazy.tsx` files to reduce initial bundle size.
</Accordion>

<Accordion title="Leverage type safety">
  Use `Route.useParams()`, `Route.useSearch()`, and `Route.useLoaderData()` for fully typed data access.
</Accordion>

## Next steps

<CardGroup cols={2}>
  <Card title="Data loading" icon="database" href="/router/guides/data-loading">
    Learn how to load data for your routes
  </Card>

  <Card title="Path params" icon="brackets-curly" href="/router/concepts/path-params">
    Master dynamic route parameters
  </Card>
</CardGroup>
