> ## 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.

# Quickstart

> Build your first TanStack Router application in minutes with this step-by-step guide

This quickstart guide will help you create a fully functional router-based React application in under 5 minutes.

## Prerequisites

Before starting, make sure you have:

* Node.js 20.19 or higher installed
* A React application set up (or create one with Vite)
* TanStack Router installed (see [Installation](/router/installation))

## Step 1: Create Your First Routes

Let's build a simple application with a home page and an about page using code-based routing.

<Steps>
  ### Import the Router Dependencies

  Start by importing the necessary functions from TanStack Router:

  ```tsx main.tsx theme={null}
  import React from 'react'
  import ReactDOM from 'react-dom/client'
  import {
    Link,
    Outlet,
    RouterProvider,
    createRootRoute,
    createRoute,
    createRouter,
  } from '@tanstack/react-router'
  ```

  ### Create the Root Route

  The root route serves as the layout wrapper for all other routes. It typically contains navigation and an `<Outlet />` where child routes render:

  ```tsx main.tsx theme={null}
  const rootRoute = createRootRoute({
    component: () => (
      <>
        <div className="p-2 flex gap-2">
          <Link to="/" className="[&.active]:font-bold">
            Home
          </Link>
          <Link to="/about" className="[&.active]:font-bold">
            About
          </Link>
        </div>
        <hr />
        <Outlet />
      </>
    ),
  })
  ```

  <Info>
    The `<Outlet />` component renders the matched child route's component. This enables nested layouts.
  </Info>

  ### Create the Index Route

  The index route renders at the root path (`/`):

  ```tsx main.tsx theme={null}
  const indexRoute = createRoute({
    getParentRoute: () => rootRoute,
    path: '/',
    component: function Index() {
      return (
        <div className="p-2">
          <h3>Welcome Home!</h3>
        </div>
      )
    },
  })
  ```

  ### Create the About Route

  Add an about page at `/about`:

  ```tsx main.tsx theme={null}
  const aboutRoute = createRoute({
    getParentRoute: () => rootRoute,
    path: '/about',
    component: function About() {
      return <div className="p-2">Hello from About!</div>
    },
  })
  ```

  ### Build the Route Tree

  Combine your routes into a tree structure:

  ```tsx main.tsx theme={null}
  const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])
  ```

  ### Create the Router Instance

  Create the router with your route tree and optional configuration:

  ```tsx main.tsx theme={null}
  const router = createRouter({
    routeTree,
    defaultPreload: 'intent',
    scrollRestoration: true,
  })
  ```

  <Tip>
    The `defaultPreload: 'intent'` option preloads routes when users hover over links, creating a snappier experience.
  </Tip>

  ### Register the Router for Type-Safety

  Register your router type for full TypeScript inference:

  ```tsx main.tsx theme={null}
  declare module '@tanstack/react-router' {
    interface Register {
      router: typeof router
    }
  }
  ```

  <Note>
    This declaration enables autocomplete for route paths, params, and search parameters throughout your application.
  </Note>

  ### Render the Application

  Finally, render your app with the `RouterProvider`:

  ```tsx main.tsx theme={null}
  const rootElement = document.getElementById('app')!

  if (!rootElement.innerHTML) {
    const root = ReactDOM.createRoot(rootElement)
    root.render(<RouterProvider router={router} />)
  }
  ```
</Steps>

## Complete Example

Here's the full code for reference:

<CodeGroup>
  ```tsx main.tsx (Code-Based) theme={null}
  import React from 'react'
  import ReactDOM from 'react-dom/client'
  import {
    Link,
    Outlet,
    RouterProvider,
    createRootRoute,
    createRoute,
    createRouter,
  } from '@tanstack/react-router'

  const rootRoute = createRootRoute({
    component: () => (
      <>
        <div className="p-2 flex gap-2">
          <Link to="/" className="[&.active]:font-bold">
            Home
          </Link>
          <Link to="/about" className="[&.active]:font-bold">
            About
          </Link>
        </div>
        <hr />
        <Outlet />
      </>
    ),
  })

  const indexRoute = createRoute({
    getParentRoute: () => rootRoute,
    path: '/',
    component: function Index() {
      return (
        <div className="p-2">
          <h3>Welcome Home!</h3>
        </div>
      )
    },
  })

  const aboutRoute = createRoute({
    getParentRoute: () => rootRoute,
    path: '/about',
    component: function About() {
      return <div className="p-2">Hello from About!</div>
    },
  })

  const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])

  const router = createRouter({
    routeTree,
    defaultPreload: 'intent',
    scrollRestoration: true,
  })

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

  const rootElement = document.getElementById('app')!
  if (!rootElement.innerHTML) {
    const root = ReactDOM.createRoot(rootElement)
    root.render(<RouterProvider router={router} />)
  }
  ```

  ```tsx routes/__root.tsx (File-Based) theme={null}
  import { Link, Outlet, createRootRoute } from '@tanstack/react-router'

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

  function RootComponent() {
    return (
      <>
        <div className="p-2 flex gap-2">
          <Link
            to="/"
            activeProps={{ className: 'font-bold' }}
            activeOptions={{ exact: true }}
          >
            Home
          </Link>
          <Link to="/about" activeProps={{ className: 'font-bold' }}>
            About
          </Link>
        </div>
        <hr />
        <Outlet />
      </>
    )
  }
  ```

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

  export const Route = createFileRoute('/')({  
    component: HomeComponent,
  })

  function HomeComponent() {
    return (
      <div className="p-2">
        <h3>Welcome Home!</h3>
      </div>
    )
  }
  ```

  ```tsx routes/about.tsx (File-Based) theme={null}
  import { createFileRoute } from '@tanstack/react-router'

  export const Route = createFileRoute('/about')({
    component: AboutComponent,
  })

  function AboutComponent() {
    return <div className="p-2">Hello from About!</div>
  }
  ```
</CodeGroup>

## Step 2: Add Data Loading

TanStack Router can load data before rendering routes. Let's add a loader to fetch posts:

```tsx theme={null}
import { createRoute } from '@tanstack/react-router'

const postsRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/posts',
  loader: async () => {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts')
    return response.json()
  },
  component: function Posts() {
    const posts = postsRoute.useLoaderData()
    
    return (
      <div className="p-2">
        <h3>Posts</h3>
        <ul>
          {posts.map((post: any) => (
            <li key={post.id}>{post.title}</li>
          ))}
        </ul>
      </div>
    )
  },
})
```

<Info>
  Loaders run before the route component renders, ensuring data is ready when your component mounts.
</Info>

## Step 3: Add Path Parameters

Create dynamic routes with type-safe path parameters:

```tsx theme={null}
const postRoute = createRoute({
  getParentRoute: () => postsRoute,
  path: '$postId',
  loader: async ({ params }) => {
    const response = await fetch(
      `https://jsonplaceholder.typicode.com/posts/${params.postId}`
    )
    return response.json()
  },
  component: function Post() {
    const post = postRoute.useLoaderData()
    
    return (
      <div className="p-2">
        <h4>{post.title}</h4>
        <p>{post.body}</p>
      </div>
    )
  },
})
```

## Step 4: Add DevTools (Optional)

Install and add the DevTools for debugging:

```tsx main.tsx theme={null}
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'

const rootRoute = createRootRoute({
  component: () => (
    <>
      <div className="p-2 flex gap-2">
        {/* navigation */}
      </div>
      <hr />
      <Outlet />
      <TanStackRouterDevtools position="bottom-right" />
    </>
  ),
})
```

<Tip>
  DevTools are automatically tree-shaken in production builds, so you can safely include them in your root route.
</Tip>

## Type-Safe Navigation

TanStack Router provides full type-safety for navigation:

```tsx theme={null}
import { Link, useNavigate } from '@tanstack/react-router'

function MyComponent() {
  const navigate = useNavigate()
  
  return (
    <div>
      {/* Type-safe Link component */}
      <Link to="/posts/$postId" params={{ postId: '1' }}>
        View Post 1
      </Link>
      
      {/* Programmatic navigation */}
      <button
        onClick={() => {
          navigate({ to: '/posts/$postId', params: { postId: '2' } })
        }}
      >
        Navigate to Post 2
      </button>
    </div>
  )
}
```

## Next Steps

Congratulations! You've built your first TanStack Router application. Here's what to explore next:

<CardGroup cols={2}>
  <Card title="Core Concepts" icon="book" href="/router/concepts/routing">
    Learn the fundamentals of routing, navigation, and data loading
  </Card>

  <Card title="File-Based Routing" icon="folder" href="/router/guides/file-based-routing">
    Organize routes by file structure with automatic generation
  </Card>

  <Card title="Search Parameters" icon="magnifying-glass" href="/router/concepts/search-params">
    Master type-safe URL search parameters as application state
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/router/guides/error-handling">
    Implement robust error boundaries and fallbacks
  </Card>
</CardGroup>

## Common Patterns

### Route-Level Code Splitting

Lazy load route components for better performance:

```tsx theme={null}
const aboutRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/about',
}).lazy(() => import('./routes/about.lazy').then((d) => d.Route))
```

### Search Parameter Validation

Add type-safe search params with validation:

```tsx theme={null}
import { z } from 'zod'
import { zodValidator } from '@tanstack/zod-adapter'

const searchRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/search',
  validateSearch: zodValidator({
    schema: z.object({
      query: z.string().optional(),
      page: z.number().default(1),
    }),
  }),
  component: function Search() {
    const { query, page } = searchRoute.useSearch()
    return <div>Searching for: {query} (page {page})</div>
  },
})
```

### Nested Layouts

Create layouts that wrap multiple child routes:

```tsx theme={null}
const dashboardRoute = createRoute({
  getParentRoute: () => rootRoute,
  path: '/dashboard',
  component: () => (
    <div className="dashboard-layout">
      <aside>Sidebar</aside>
      <main>
        <Outlet />
      </main>
    </div>
  ),
})

const dashboardIndexRoute = createRoute({
  getParentRoute: () => dashboardRoute,
  path: '/',
  component: () => <div>Dashboard Home</div>,
})
```

<Warning>
  Make sure to include `<Outlet />` in parent routes to render child route content.
</Warning>
