### TanStack Router Quickstart Setup
Source: https://tanstack.com/router/latest/docs/framework/react/examples/quickstart
This code sets up the basic structure for a React application using TanStack Router. It includes creating root and index routes, defining navigation links, and integrating the router with React's ReactDOM. Ensure you have the necessary dependencies installed.
```tsx
import React, { StrictMode } from 'react'
import ReactDOM from 'react-dom/client'
import {
Link,
Outlet,
RouterProvider,
createRootRoute,
createRoute,
createRouter,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import './styles.css'
const rootRoute = createRootRoute({
component: () => (
<>
},
})
const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])
const router = createRouter({ routeTree })
declare module '@tanstack/solid-router' {
interface Register {
router: typeof router
}
}
const rootElement = document.getElementById('app')!
render(() => , rootElement)
```
--------------------------------
### Install with Deno
Source: https://tanstack.com/router/latest/docs/how-to/install.md
Use this command to install TanStack Router with Deno.
```bash
deno add npm:@tanstack/react-router
```
--------------------------------
### Install Auth0 SDK
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Install the Auth0 React SDK using npm.
```bash
npm install @auth0/auth0-react
```
--------------------------------
### Kitchen Sink React Query Example
Source: https://tanstack.com/router/latest/docs/framework/react/examples/kitchen-sink-react-query
This is the main entry point for the Kitchen Sink example, setting up the router, query client, and root route with context. It includes imports for both TanStack Router and React Query, along with utility functions and mock data.
```tsx
/* eslint-disable @typescript-eslint/no-unnecessary-condition */
import * as React from 'react'
import ReactDOM from 'react-dom/client'
import {
ErrorComponent,
Link,
MatchRoute,
Outlet,
RouterProvider,
createRootRouteWithContext,
createRoute,
createRouter,
lazyRouteComponent,
redirect,
retainSearchParams,
useNavigate,
useRouter,
useRouterState,
useSearch,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import {
QueryClient,
QueryClientProvider,
queryOptions,
useMutation,
useSuspenseQuery,
} from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import { z } from 'zod'
import {
fetchInvoiceById,
fetchInvoices,
fetchUserById,
fetchUsers,
patchInvoice,
postInvoice,
} from './mockTodos'
import type { Invoice } from './mockTodos'
import './styles.css'
//
type UsersViewSortBy = 'name' | 'id' | 'email'
const invoicesQueryOptions = () =>
queryOptions({
queryKey: ['invoices'],
queryFn: () => fetchInvoices(),
})
const invoiceQueryOptions = (invoiceId: number) =>
queryOptions({
queryKey: ['invoices', invoiceId],
queryFn: () => fetchInvoiceById(invoiceId),
})
const usersQueryOptions = ({
filterBy,
sortBy,
}: { filterBy?: string; sortBy?: UsersViewSortBy })
=>
queryOptions({
queryKey: ['users', { filterBy, sortBy }],
queryFn: () =>
fetchUsers({
filterBy,
sortBy,
}),
})
const userQueryOptions = (userId: number) =>
queryOptions({
queryKey: ['users', userId],
queryFn: async () => {
const user = await fetchUserById(userId)
if (!user) {
throw new Error('User not found.')
}
return user
},
})
const useCreateInvoiceMutation = () => {
return useMutation({
mutationKey: ['invoices', 'create'],
mutationFn: postInvoice,
onSuccess: () => queryClient.invalidateQueries(),
})
}
const useUpdateInvoiceMutation = (invoiceId: number) => {
return useMutation({
mutationKey: ['invoices', 'update', invoiceId],
mutationFn: patchInvoice,
onSuccess: () => queryClient.invalidateQueries(),
gcTime: 1000 * 10,
})
}
function RouterSpinner() {
const isLoading = useRouterState({ select: (s) => s.status === 'pending' })
return
}
// Routes
// Build our routes. We could do this in our component, too.
const rootRoute = createRootRouteWithContext<{
auth: Auth
queryClient: QueryClient
}>()({
component: RootComponent,
})
```
--------------------------------
### Install Solid Router Devtools
Source: https://tanstack.com/router/latest/docs/devtools.md
Install the Solid devtools package using npm or yarn.
```bash
npm install @tanstack/solid-router-devtools
yarn add @tanstack/solid-router-devtools
```
--------------------------------
### Install Supabase JS Client
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Install the Supabase JavaScript client library using npm.
```bash
npm install @supabase/supabase-js
```
--------------------------------
### React Router Setup
Source: https://tanstack.com/router/latest/docs/framework/react/examples/deferred-data
Initializes the React application by creating a root element and rendering the RouterProvider with the configured router.
```javascript
const rootElement = document.getElementById('app')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render()
}
```
--------------------------------
### Project Structure Example
Source: https://tanstack.com/router/latest/docs/routing/virtual-file-routes.md
Illustrates a project structure that mixes file-based routing with virtual route configuration.
```treeview
├── __root.tsx
├── index.tsx
├── posts
│ ├── __virtual.ts
│ ├── details.tsx
│ ├── home.tsx
│ └── lets-go
│ ├── deeper
│ │ ├── __virtual.ts
│ │ └── home.tsx
│ └── index.tsx
└── posts.tsx
```
--------------------------------
### useBlocker with Custom UI
Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md
Implement custom UI prompts for navigation blocking. This example uses `withResolver: true` to get `proceed` and `reset` functions for user interaction.
```tsx
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
const { proceed, reset, status, next } = useBlocker({
shouldBlockFn: () => formIsDirty,
withResolver: true,
})
// ...
return (
<>
{/* ... */}
{status === 'blocked' && (
You are navigating to {next.pathname}
Are you sure you want to leave?
)}
>
}
```
--------------------------------
### Install with bun
Source: https://tanstack.com/router/latest/docs/how-to/install.md
Use this command to install TanStack Router with bun.
```bash
bun add @tanstack/react-router
```
--------------------------------
### Install Clerk React SDK
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Install the Clerk React SDK using npm. This is the first step to integrate Clerk authentication.
```bash
npm install @clerk/clerk-react
```
--------------------------------
### Install React Router Devtools
Source: https://tanstack.com/router/latest/docs/devtools.md
Install the React devtools package using npm or yarn.
```bash
npm install @tanstack/react-router-devtools
yarn add @tanstack/react-router-devtools
```
--------------------------------
### Basic Devtools Panel Setup with React Router and React Query
Source: https://tanstack.com/router/latest/docs/framework/react/examples/basic-devtools-panel
This snippet shows the complete setup for a basic React application using TanStack Router and React Query. It includes route definitions, router creation, and the integration of TanStack Router Devtools Panel, rendering it within a Shadow DOM.
```tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
import {
Outlet,
RouterProvider,
Link,
createRouter,
createRoute,
createRootRoute,
} from '@tanstack/react-router'
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
import './styles.css'
const rootRoute = createRootRoute({
component: () => (
<>
},
})
const routeTree = rootRoute.addChildren([indexRoute, aboutRoute])
const router = createRouter({ routeTree })
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(
,
)
}
```
--------------------------------
### Splat Route Parameters Example
Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md
Demonstrates the structure of the params object for a splat route, showing how a URL is captured under the `_splat` key.
```js
{
'_splat': 'documents/hello-world'
}
```
--------------------------------
### Example Usage of useConditionalNavigate
Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md
Demonstrates how to use the `useConditionalNavigate` hook with specific navigation options. The `navigateOptions` are type-safe.
```tsx
const { enable, disable, navigate } = useConditionalNavigate({
to: '/posts/$postId',
params: { postId: 'postId' },
})
```
--------------------------------
### Route Matching Example: /
Source: https://tanstack.com/router/latest/docs/routing/route-matching.md
Shows the root route '/' being matched directly as the most specific static route at the root level.
```plaintext
Root
✅ /
- about/us
- about
- blog
- /
- new
- $postId
- *
```
--------------------------------
### Server Middleware Configuration
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Example of configuring URL rewrites in the router for server-side request parsing.
```APIDOC
## Server Middleware Configuration
### Description
Configure bidirectional URL transformation for incoming requests and outgoing responses.
### Method
`createRouter` with `rewrite` option
### Endpoint
N/A (Configuration within router setup)
### Parameters
#### Router Options
- **rewrite** (`LocationRewrite`): Optional. Configures bidirectional URL transformation.
- **input** (`LocationRewriteFunction`): Optional. Transforms URL before router interpretation (e.g., for browser history).
- **output** (`LocationRewriteFunction`): Optional. Transforms URL before writing to browser history (e.g., for links and navigation).
### Request Example
```tsx
// router.tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree'
// Assume deLocalizeUrl and localizeUrl are defined elsewhere
const deLocalizeUrl = (url: URL) => url;
const localizeUrl = (url: URL) => url;
export const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => deLocalizeUrl(url),
output: ({ url }) => localizeUrl(url),
},
})
```
### Response
N/A (This is a configuration, not an endpoint call.)
```
--------------------------------
### Navigate to File with Optional Name
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Example of navigating to a URL with a prefix, an optional parameter (`name`), and a suffix (`.txt`), providing a value for the optional parameter.
```tsx
// Navigate to file with optional name
Document File
```
--------------------------------
### Install TanStack Router
Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-router.md
Install the TanStack Router package using npm. Refer to the detailed installation guide for more information.
```bash
npm i @tanstack/react-router
```
--------------------------------
### Basic React Application Setup
Source: https://tanstack.com/router/latest/docs/framework/react/examples/quickstart
This snippet shows the basic structure for rendering a React application. It includes setting up the root element and using ReactDOM to render your application. Ensure the 'app' element exists in your HTML.
```typescript
'@tanstack/react-router' { interface Register { router: typeof router } }
const rootElement = document.getElementById('app')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render(
,
)
}
```
--------------------------------
### React Router Setup with TanStack Router
Source: https://tanstack.com/router/latest/docs/framework/react/examples/scroll-restoration
This code sets up the root React element and renders the `RouterProvider` with the configured router. It ensures that the application starts correctly with scroll restoration enabled.
```javascript
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(
,
)
}
```
--------------------------------
### Recommended Flat Config Setup
Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md
Enables all recommended rules for the TanStack Router ESLint plugin using ESLint's flat config format. Ensure you have installed the plugin as a dev dependency.
```js
import pluginRouter from '@tanstack/eslint-plugin-router'
export default [
...pluginRouter.configs['flat/recommended'],
// Any other config...
]
```
--------------------------------
### Route File Naming Conventions Example
Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md
Demonstrates how route files and co-located non-route files can be organized within the routes directory, using a prefix to ignore certain files.
```txt
src/routes
├── posts
│ ├── -components // Ignored
│ │ ├── Post.tsx
│ ├── index.tsx
│ ├── route.tsx
```
--------------------------------
### Accessing Search Parameters with useSearch
Source: https://tanstack.com/router/latest/docs/api/router/useSearchHook.md
Demonstrates how to use the useSearch hook to retrieve current search query parameters. It shows examples of getting the full search object, selecting a specific property, and accessing parameters with strictness disabled.
```tsx
import { useSearch } from '@tanstack/react-router'
function Component() {
const search = useSearch({ from: '/posts/$postId' })
// ^ FullSearchSchema
// OR
const selected = useSearch({
from: '/posts/$postId',
select: (search) => search.postView,
})
// ^ string
// OR
const looseSearch = useSearch({ strict: false })
// ^ Partial
// ...
}
```
--------------------------------
### Main App Setup with AuthProvider
Source: https://tanstack.com/router/latest/docs/framework/react/examples/authenticated-routes
Sets up the main application component, wrapping the router with an AuthProvider to manage authentication state. Requires `auth.tsx` for the AuthProvider implementation.
```jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
import { AuthProvider, useAuth } from './auth'
import './styles.css'
// Set up a Router instance
const router = createRouter({
routeTree,
defaultPreload: 'intent',
scrollRestoration: true,
context: {
auth: undefined!, // This will be set after we wrap the app in an AuthProvider
},
})
// Register things for typesafety
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
function InnerApp() {
const auth = useAuth()
return
}
function App() {
return (
)
}
const rootElement = document.getElementById('app')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render(
,
)
}
```
--------------------------------
### Router Setup and Rendering
Source: https://tanstack.com/router/latest/docs/framework/react/examples/navigation-blocking
This snippet shows the creation of the route tree, router instance, and rendering the application using `RouterProvider` with React 19's `createRoot`.
```jsx
const routeTree = rootRoute.addChildren([
indexRoute,
fooRoute,
editor1Route.addChildren([editor2Route]),
])
// Set up a Router instance
const router = createRouter({
routeTree,
defaultPreload: 'intent',
scrollRestoration: true,
})
const rootElement = document.getElementById('app')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render()
}
```
--------------------------------
### React Router Setup
Source: https://tanstack.com/router/latest/docs/framework/react/examples/quickstart
Sets up the root route, creates a router, and configures the React application to use the router. Includes basic navigation links and the Outlet for nested routes.
```tsx
import React, { StrictMode } from 'react'
import ReactDOM from 'react-dom/client'
import {
Link,
Outlet,
RouterProvider,
createRootRoute,
createRoute,
createRouter,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from
'@tanstack/react-router-devtools'
import './styles.css'
const rootRoute = createRootRoute({
component: () => (
<>
}
const queryErrorResetBoundary = useQueryErrorResetBoundary()
```
--------------------------------
### Create Router Instance
Source: https://tanstack.com/router/latest/docs/framework/react/examples/location-masking
Initializes the router with the defined route tree, route masks, and configuration options like default preloading and scroll restoration.
```javascript
// Set up a Router instance
const router = createRouter({
routeTree,
routeMasks: [photoModalToPhotoMask],
defaultPreload: 'intent',
scrollRestoration: true,
})
```
--------------------------------
### Install TanStack Router CLI
Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md
Install the `@tanstack/router-cli` package as a development dependency for file-based routing.
```bash
npm install @tanstack/router-cli -D
solid: @tanstack/router-cli
```
--------------------------------
### Example of Serialized Search String
Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md
This is an example of a search string generated using the zipson serialization configuration.
```txt
?page=1&sort=asc&filters=JTdCJUMyJUE4YXV0aG9yJUMyJUE4JUMyJUE4dGFubmVyJUMyJUE4JUMyJUE4bWluX3dvcmRzJUMyJUE4JUMyJUEyQ3UlN0Q%3D
```
--------------------------------
### Basic React Router Setup
Source: https://tanstack.com/router/latest/docs/framework/react/examples/basic
This snippet sets up the root route, navigation links, and includes the TanStack Router Devtools. It also defines a catch-all notFoundComponent for the root.
```jsx
import ReactDOM from 'react-dom/client'
import {
ErrorComponent,
Link,
Outlet,
RouterProvider,
createRootRoute,
createRoute,
createRouter,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
import { NotFoundError, fetchPost, fetchPosts } from './posts'
import type { ErrorComponentProps } from '@tanstack/react-router'
import './styles.css'
const rootRoute = createRootRoute({
component: RootComponent,
notFoundComponent: () => {
return (
This is the notFoundComponent configured on root route
Start Over
)
},
})
function RootComponent() {
return (
<>
Home
{' '}
Posts
{' '}
Pathless Layout
{' '}
This Route Does Not Exist
}
return
}
function PostComponent() {
const post = postRoute.useLoaderData()
return (
{post.title}
{post.body}
)
}
const pathlessLayoutRoute = createRoute({
getParentRoute: () => rootRoute,
id: '_pathlessLayout',
component: PathlessLayoutComponent,
})
```
--------------------------------
### Main Application Setup with AuthProvider
Source: https://tanstack.com/router/latest/docs/framework/react/examples/authenticated-routes
Sets up the main React application, including the TanStack Router and wrapping the application with the AuthProvider. This ensures authentication context is available globally.
```typescript
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
import { AuthProvider, useAuth } from './auth'
import './styles.css'
// Set up a Router instance
const router = createRouter({
routeTree,
defaultPreload: 'intent',
scrollRestoration: true,
context: {
auth: undefined!, // This will be set after we wrap the app in an AuthProvider
},
})
// Register things for typesafety
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
function InnerApp() {
const auth = useAuth()
return (
)
}
function App() {
return (
)
}
const rootElement = document.getElementById('app')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render()
}
```
--------------------------------
### Install TanStack Router Dependencies
Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md
Install the necessary TanStack Router packages using npm. This replaces React Location dependencies.
```sh
npm install @tanstack/react-router @tanstack/router-devtools
```
```sh
npm uninstall @tanstack/react-location @tanstack/react-location-devtools
```
--------------------------------
### Create Solid Router with Context
Source: https://tanstack.com/router/latest/docs/guide/router-context.md
Set up a Solid router with a typed context to pass down a QueryClient instance.
```tsx
import {
createRootRouteWithContext,
createRouter,
} from '@tanstack/solid-router'
interface MyRouterContext {
queryClient: QueryClient
}
const rootRoute = createRootRouteWithContext()({
component: App,
})
const queryClient = new QueryClient()
const router = createRouter({
routeTree: rootRoute,
context: {
queryClient,
},
})
```
--------------------------------
### Install TanStack Solid Router
Source: https://tanstack.com/router/latest/docs/quick-start.md
Install the TanStack Solid Router package into an existing Solid project using npm, yarn, or pnpm.
```bash
@tanstack/solid-router
```
--------------------------------
### Install TanStack React Router
Source: https://tanstack.com/router/latest/docs/quick-start.md
Install the TanStack React Router package into an existing React project using npm, yarn, or pnpm.
```bash
@tanstack/react-router
```
--------------------------------
### Main Application Entry Point
Source: https://tanstack.com/router/latest/docs/framework/react/examples/with-trpc-react-query
Sets up the React application and renders the TanStack Router. This is the main entry point for the application, responsible for initializing the router and rendering it within the React DOM.
```tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider } from '@tanstack/react-router'
import './styles.css'
import { createRouter } from './router'
// Set up a Router instance
const router = createRouter()
const rootElement = document.getElementById('root')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render(
,
)
}
```
--------------------------------
### Example of Binary Encoded Search String
Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md
This example shows how a JavaScript object, when serialized using the custom binary encoding functions, appears as a URL-encoded string.
```txt
?page=1&sort=asc&filters=eyJhdXRob3IiOiJ0YW5uZXIiLCJtaW5fd29yZHMiOjg4MH0%3D
```
--------------------------------
### Get Current Location with useLocation
Source: https://tanstack.com/router/latest/docs/api/router/useLocationHook.md
Import and use the `useLocation` hook to get the current location object. This is useful for performing side effects based on location changes.
```tsx
import { useLocation } from '@tanstack/react-router'
function Component() {
const location = useLocation()
// ^ ParsedLocation
// ...
}
```
--------------------------------
### Basic Root Route Setup in Solid
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
Sets up the basic root route component for a Solid application using TanStack Router. Includes essential imports for routing and scripts.
```tsx
import { createFileRoute, Scripts } from '@tanstack/solid-router'
export const Route = createRootRoute('/')({
component: () => (
),
})
```
--------------------------------
### Initialize React Router with React Query
Source: https://tanstack.com/router/latest/docs/framework/react/examples/basic-react-query-file-based
Sets up the QueryClient and creates a Router instance, passing the QueryClient to the router's context. Configures default preload behavior and scroll restoration.
```tsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createRouter } from '@tanstack/react-router'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { routeTree } from './routeTree.gen'
import './styles.css'
const queryClient = new QueryClient()
// Set up a Router instance
const router = createRouter({
routeTree,
context: {
queryClient,
},
defaultPreload: 'intent',
// Since we're using React Query, we don't want loader calls to ever be stale
// This will ensure that the loader is always called when the route is preloaded or visited
defaultPreloadStaleTime: 0,
scrollRestoration: true,
})
// Register things for typesafety
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(
,
)
}
```
--------------------------------
### React Router Setup with Location Masking
Source: https://tanstack.com/router/latest/docs/framework/react/examples/location-masking
This snippet shows the basic setup for TanStack Router in a React application, including type registration and rendering the RouterProvider. Location masking itself is typically configured within the route definitions, which are not shown in this specific snippet.
```tsx
// Register things for typesafety
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()
}
```