### Install Auth0 SDK
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Install the Auth0 React SDK using npm. This is the first step to integrate Auth0 authentication.
```bash
npm install @auth0/auth0-react
```
--------------------------------
### Verify package installation
Source: https://tanstack.com/router/latest/docs/quick-start.md
Check the dependencies section of your package.json to confirm the router is installed.
```json
{
"dependencies": {
"@tanstack/react-router": "^x.x.x"
}
}
```
```json
{
"dependencies": {
"@tanstack/solid-router": "^x.x.x"
}
}
```
--------------------------------
### Install Supabase Client
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Installs the Supabase JavaScript client library using npm. This is the first step to integrating Supabase services.
```bash
npm install @supabase/supabase-js
```
--------------------------------
### Start/Full-Stack Applications - Solid
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
Example of rendering `` in a Solid full-stack application.
```APIDOC
## Start/Full-Stack Applications - Solid
### Description
Example of rendering `` in a Solid full-stack application.
### Method
N/A (Component Integration)
### Endpoint
N/A (Component Integration)
### Request Example
```tsx
import { HeadContent } from '@tanstack/solid-router'
export const Route = createRootRoute({
component: () => (
),
})
```
### Response
N/A (Component Integration)
```
--------------------------------
### Install Clerk SDK
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Install the Clerk React SDK using npm. This is required for Clerk integration.
```bash
npm install @clerk/clerk-react
```
--------------------------------
### Menu Component Usage Example
Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md
Example of how to use the Menu component with relative navigation options.
```tsx
```
--------------------------------
### Start/Full-Stack Applications - React
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
Example of rendering `` in a React full-stack application.
```APIDOC
## Start/Full-Stack Applications - React
### Description
Example of rendering `` in a React full-stack application.
### Method
N/A (Component Integration)
### Endpoint
N/A (Component Integration)
### Request Example
```tsx
import { HeadContent } from '@tanstack/react-router'
export const Route = createRootRoute({
component: () => (
),
})
```
### Response
N/A (Component Integration)
```
--------------------------------
### Install vibe-rules Globally
Source: https://tanstack.com/router/latest/docs/llm-support.md
Install `vibe-rules` globally using pnpm. This command is used to set up the LLM assistance rules for TanStack Router.
```bash
pnpm add -g vibe-rules
```
--------------------------------
### Install vibe-rules for Cursor
Source: https://tanstack.com/router/latest/docs/llm-support.md
Integrate `vibe-rules` with the Cursor editor. This command enables context-aware help within Cursor.
```bash
vibe-rules install cursor
```
--------------------------------
### createLink Basic Example (Solid)
Source: https://tanstack.com/router/latest/docs/guide/custom-link.md
Demonstrates how to create a custom Link component in Solid.js using `createLink`, enabling custom styling and behavior with type safety.
```APIDOC
## createLink Basic Example (Solid)
### Description
This example illustrates creating a custom `Link` component in Solid.js using `createLink`. It allows for custom props and styles while maintaining type safety provided by TanStack Router.
### Method
N/A (This is a component creation example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```tsx
import * as Solid from 'solid-js';
import { createLink, LinkComponent } from '@tanstack/solid-router';
export const Route = createRootRoute({
component: RootComponent,
});
type BasicLinkProps = Solid.JSX.IntrinsicElements['a'] & {
// Add any additional props you want to pass to the anchor element
}
const BasicLinkComponent: Solid.Component = (props) => (
{props.children}
)
const CreatedLinkComponent = createLink(BasicLinkComponent)
export const CustomLink: LinkComponent = (props) => {
return
}
```
### Response
N/A (This is a component creation example)
```
--------------------------------
### fetchOrRedirect Usage Example
Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md
Example demonstrating the type-safe usage of the fetchOrRedirect function with a redirect option.
```tsx
fetchOrRedirect('http://example.com/', { to: '/login' })
```
--------------------------------
### Single-Page Applications - Solid
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
Example of rendering `` in a Solid single-page application.
```APIDOC
## Single-Page Applications - Solid
### Description
Example of rendering `` in a Solid single-page application. Ensure the `` tag is removed from `index.html` if present.
### Method
N/A (Component Integration)
### Endpoint
N/A (Component Integration)
### Request Example
```tsx
import { HeadContent } from '@tanstack/solid-router'
const rootRoute = createRootRoute({
component: () => (
<>
>
),
})
```
### Response
N/A (Component Integration)
```
--------------------------------
### Install TanStack Router CLI
Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md
Install the TanStack Router CLI as a development dependency for your project.
```bash
npm install @tanstack/router-cli --save-dev
```
```bash
yarn add @tanstack/router-cli --dev
```
```bash
pnpm add @tanstack/router-cli --save-dev
```
--------------------------------
### 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
```
--------------------------------
### createLink Basic Example (React)
Source: https://tanstack.com/router/latest/docs/guide/custom-link.md
Demonstrates how to create a basic custom Link component in React using `createLink` for custom styling and behavior while maintaining type safety.
```APIDOC
## createLink Basic Example (React)
### Description
This example shows how to create a custom `Link` component in React using `createLink`. It allows for adding custom props and styles while preserving the type safety of TanStack Router.
### Method
N/A (This is a component creation example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```tsx
import * as React from 'react';
import { createLink, LinkComponent } from '@tanstack/react-router';
interface BasicLinkProps extends React.AnchorHTMLAttributes {
// Add any additional props you want to pass to the anchor element
}
const BasicLinkComponent = React.forwardRef(
(props, ref) => {
return (
);
},
);
const CreatedLinkComponent = createLink(BasicLinkComponent);
export const CustomLink: LinkComponent = (props) => {
return ;
}
```
### Response
N/A (This is a component creation example)
### Usage Example
```tsx
```
```
--------------------------------
### Recommended Flat Config Setup for ESLint
Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md
Configure ESLint using the flat config format to enable all recommended rules provided by the TanStack Router ESLint plugin. This setup assumes ESLint 9.0 or later.
```javascript
import pluginRouter from '@tanstack/eslint-plugin-router'
export default [
...pluginRouter.configs['flat/recommended'],
// Any other config...
]
```
--------------------------------
### Define a File-Based Route with createFileRoute
Source: https://tanstack.com/router/latest/docs/api/router/createFileRouteFunction.md
This example demonstrates how to initialize a route using createFileRoute. It includes a loader function and a component that consumes the loader data via the useLoaderData hook.
```tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/')({
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return
{data}
}
```
--------------------------------
### Usage of useConditionalNavigate
Source: https://tanstack.com/router/latest/docs/guide/type-utilities.md
Example of initializing the hook with type-safe navigation options.
```tsx
const { enable, disable, navigate } = useConditionalNavigate({
to: '/posts/$postId',
params: { postId: 'postId' },
})
```
--------------------------------
### Using Mutation Keys for State Reset
Source: https://tanstack.com/router/latest/docs/guide/data-mutations.md
This example demonstrates how to use a keying mechanism with mutations to automatically reset their state when relevant parameters (like roomId) change.
```APIDOC
## Using Mutation Keys
### Description
This section illustrates how to leverage a keying mechanism provided by a mutation library to reset mutation state when a key changes. This is particularly useful for clearing submission and loading states related to specific data or routes.
### Method
Not applicable (Client-side logic)
### Endpoint
Not applicable (Client-side logic)
### Parameters
Not applicable
### Request Example
```tsx
const routeApi = getRouteApi('/room/$roomId/chat')
function ChatRoom() {
const { roomId } = routeApi.useParams()
const sendMessageMutation = useCoolMutation({
fn: sendMessage,
// Clear the mutation state when the roomId changes
// including any submission state
key: ['sendMessage', roomId],
})
// Fire off a bunch of messages
const test = () => {
sendMessageMutation.mutate({ roomId, message: 'Hello!' })
sendMessageMutation.mutate({ roomId, message: 'How are you?' })
sendMessageMutation.mutate({ roomId, message: 'Goodbye!' })
}
return (
<>
{sendMessageMutation.submissions.map((submission) => (
{submission.status}
{submission.message}
))}
>
)
}
```
### Response
Not applicable (Client-side logic)
```
--------------------------------
### Example Component Tree Rendering
Source: https://tanstack.com/router/latest/docs/routing/route-trees.md
Demonstrates the component hierarchy rendered by TanStack Router based on a nested route structure.
```tsx
```
--------------------------------
### Programmatic Navigation with useNavigate
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Programmatic navigation using `navigate()` respects output rewrites. This example demonstrates navigating to '/about', which will be displayed as '/en/about' in the browser due to rewrites.
```tsx
const navigate = useNavigate()
// Navigates to /about internally, displays /en/about in browser
navigate({ to: '/about' })
```
--------------------------------
### Initialize Root Route and Router
Source: https://tanstack.com/router/latest/docs/api/router/createRootRouteFunction.md
This example demonstrates how to create a root route using createRootRoute, define a component for the root outlet, and integrate it into a router instance. It shows the standard pattern for building a route tree by adding children to the root route.
```tsx
import { createRootRoute, createRouter, Outlet } from '@tanstack/react-router';
const rootRoute = createRootRoute({
component: () => ,
});
const routeTree = rootRoute.addChildren([
// ... other routes
]);
const router = createRouter({
routeTree,
});
```
--------------------------------
### Link Component Active State Examples
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Demonstrates various scenarios of Link component usage and how their active states are determined based on the current route and provided options.
```tsx
const link1 = (
Blog Post
)
const link2 = Blog Post
const link3 = Blog Post
```
```tsx
const link4 = (
Blog Post
)
```
```tsx
const link = (
Home
)
```
--------------------------------
### Server-side Considerations: Server Middleware
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Explains how URL rewrites are applied on the server when using TanStack Start, specifically how they are handled during request parsing.
```APIDOC
## Server-side Considerations
URL rewrites apply on both client and server. When using TanStack Start:
### Server Middleware
Rewrites are applied when parsing incoming requests:
### Request Example
```tsx
// router.tsx
export const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => deLocalizeUrl(url),
output: ({ url }) => localizeUrl(url),
},
})
```
The server handler will use the same rewrite configuration to parse incoming URLs and generate responses with the correct external URLs.
```
--------------------------------
### Create and Configure NotFoundRoute in React
Source: https://tanstack.com/router/latest/docs/api/router/NotFoundRouteClass.md
This example demonstrates how to create a NotFoundRoute instance and configure it with a custom component. It then integrates this into the TanStack Router setup. Note that this class is deprecated.
```tsx
import { NotFoundRoute, createRouter } from '@tanstack/react-router'
import { Route as rootRoute } from './routes/__root'
import { routeTree } from './routeTree.gen'
const notFoundRoute = new NotFoundRoute({
getParentRoute: () => rootRoute,
component: () =>
Not found!!!
,
})
const router = createRouter({
routeTree,
notFoundRoute,
})
// ... other code
```
--------------------------------
### Install TanStack Router package
Source: https://tanstack.com/router/latest/docs/quick-start.md
Add the required router package to your existing project dependencies.
```bash
@tanstack/react-router
```
```bash
@tanstack/solid-router
```
--------------------------------
### Server Middleware with Input/Output Rewrites
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
URL rewrites are applied on both client and server. This example shows server middleware configuration for input and output rewrites, using `deLocalizeUrl` and `localizeUrl`.
```tsx
// router.tsx
export const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => deLocalizeUrl(url),
output: ({ url }) => localizeUrl(url),
},
})
```
--------------------------------
### Single-Page Applications - React
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
Example of rendering `` in a React single-page application.
```APIDOC
## Single-Page Applications - React
### Description
Example of rendering `` in a React single-page application. Ensure the `` tag is removed from `index.html` if present.
### Method
N/A (Component Integration)
### Endpoint
N/A (Component Integration)
### Request Example
```tsx
import { HeadContent } from '@tanstack/react-router'
const rootRoute = createRootRoute({
component: () => (
<>
>
),
})
```
### Response
N/A (Component Integration)
```
--------------------------------
### Directory Structure for Pathless Route Groups
Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md
This example shows a typical file structure using pathless route group directories. The `(app)` and `(auth)` directories are purely for organization and do not influence routing.
```directory
routes/
├── index.tsx
├── (app)/
│ ├── dashboard.tsx
│ ├── settings.tsx
│ ├── users.tsx
├── (auth)/
│ ├── login.tsx
│ ├── register.tsx
```
--------------------------------
### Defining a Route with the Route Class
Source: https://tanstack.com/router/latest/docs/api/router/RouteClass.md
This example demonstrates how to instantiate a new Route using the Route class constructor. It includes defining the parent route, path, a loader function, and a React component that consumes the loader data.
```tsx
import { Route } from '@tanstack/react-router'
import { rootRoute } from './__root'
const indexRoute = new Route({
getParentRoute: () => rootRoute,
path: '/',
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = indexRoute.useLoaderData()
return
{data}
}
```
--------------------------------
### Define a pseudo route tree
Source: https://tanstack.com/router/latest/docs/routing/route-matching.md
An example of an unsorted route tree structure.
```text
Root
- blog
- $postId
- /
- new
- /
- *
- about
- about/us
```
--------------------------------
### 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
```
--------------------------------
### Navigate with Path Params (Object Style)
Source: https://tanstack.com/router/latest/docs/guide/path-params.md
Provides an example of navigating to a route with path parameters using an object literal for the `params` prop in the `Link` component.
```tsx
function Component() {
return (
Post 123
)
}
```
--------------------------------
### Example Nested Route Structure
Source: https://tanstack.com/router/latest/docs/routing/route-trees.md
Illustrates a hierarchical route structure for a blog section, showing how nested URLs map to nested components.
```tsx
├── blog
│ ├── posts
│ │ ├── $postId
```
--------------------------------
### Setup TanStack Router with SSR Query Integration (React)
Source: https://tanstack.com/router/latest/docs/integrations/query.md
Configure your router with a new QueryClient and set up the SSR query integration. Ensure a fresh QueryClient is created per request in SSR environments. The integration can optionally wrap your router with QueryClientProvider.
```tsx
import { QueryClient } from '@tanstack/react-query'
import { createRouter } from '@tanstack/react-router'
import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query'
import { routeTree } from './routeTree.gen'
export function getRouter() {
const queryClient = new QueryClient()
const router = createRouter({
routeTree,
// optionally expose the QueryClient via router context
context: { queryClient },
scrollRestoration: true,
defaultPreload: 'intent',
})
setupRouterSsrQueryIntegration({
router,
queryClient,
// optional:
// handleRedirects: true,
// wrapQueryClient: true,
})
return router
}
```
--------------------------------
### Implementing a Root Route with Outlet
Source: https://tanstack.com/router/latest/docs/guide/outlets.md
This example demonstrates how to define a root route component that includes a static header and an Outlet component where nested child routes will be injected. It shows the implementation for both React and Solid frameworks.
```tsx
import { createRootRoute, Outlet } from '@tanstack/react-router'
export const Route = createRootRoute({
component: RootComponent,
})
function RootComponent() {
return (
)
}
```
--------------------------------
### Get Type-Safe Route Hooks with getRouteApi (TypeScript/React)
Source: https://tanstack.com/router/latest/docs/api/router/getRouteApiFunction.md
Demonstrates how to use the getRouteApi function to obtain a RouteApi instance. This instance provides type-safe access to hooks like useLoaderData, pre-bound to a specific route ID ('/posts' in this example). This simplifies data fetching and manipulation within components tied to that route.
```tsx
import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/posts')
export function PostsPage() {
const posts = routeApi.useLoaderData()
// ...
}
```
--------------------------------
### Install TanStack Router ESLint Plugin
Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md
Install the TanStack Router ESLint plugin as a development dependency. This plugin helps enforce best practices and prevent common mistakes when using TanStack Router.
```bash
npm install -D @tanstack/eslint-plugin-router
yarn add -D @tanstack/eslint-plugin-router
pnpm add -D @tanstack/eslint-plugin-router
```
--------------------------------
### Subscribing to Router Events
Source: https://tanstack.com/router/latest/docs/api/router/RouterEventsType.md
An example demonstrating how to subscribe to router events, specifically the 'onResolved' event, and access its payload.
```APIDOC
## Example
```typescript
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({ routeTree })
const unsub = router.subscribe('onResolved', (evt) => {
// ...
})
```
```
--------------------------------
### Solid Authentication using Context and Hooks
Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md
This example demonstrates how to integrate authentication state managed by Solid context and hooks into TanStack Router. It involves defining a router context, passing the authentication state down via the RouterProvider, and using it to protect routes.
```tsx
import { createRootRouteWithContext, Outlet } from '@tanstack/solid-router';
interface MyRouterContext {
auth: AuthState
}
export const Route = createRootRouteWithContext()({
component: () => ,
});
```
```tsx
import { createRouter } from '@tanstack/solid-router';
import { routeTree } from './routeTree.gen';
export const router = createRouter({
routeTree,
context: {
auth: undefined!,
},
});
```
```tsx
import { RouterProvider } from '@tanstack/solid-router';
import { AuthProvider, useAuth } from './auth';
import { router } from './router';
function InnerApp() {
const auth = useAuth();
return ;
}
function App() {
return (
);
}
```
--------------------------------
### useBlocker with Custom UI and Resolver
Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md
This example shows how to use the useBlocker hook with 'withResolver: true' to enable custom UI feedback. When navigation is blocked, it displays a confirmation message and provides 'proceed' and 'reset' buttons 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?
)}
>
)
}
```
--------------------------------
### TanStack Start Server Middleware for i18n
Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md
Implements server-side internationalization using Paraglide's middleware in a TanStack Start application. This ensures locale is handled correctly during server requests.
```ts
import { paraglideMiddleware } from './paraglide/server'
export default {
fetch(req: Request) {
return paraglideMiddleware(req, () => handler.fetch(req))
},
}
```
--------------------------------
### composeRewrites Function Example
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Demonstrates how to use the `composeRewrites` function to combine multiple rewrite configurations into a single one. Input rewrites execute sequentially, while output rewrites execute in reverse order.
```typescript
import { composeRewrites } from '@tanstack/react-router'
function composeRewrites(rewrites: Array): LocationRewrite
const composedRewrite = composeRewrites([
{ input: rewrite1Input, output: rewrite1Output },
{ input: rewrite2Input, output: rewrite2Output },
])
// Input execution order: rewrite1Input → rewrite2Input
// Output execution order: rewrite2Output → rewrite1Output
```
--------------------------------
### createLink with MUI (Material-UI)
Source: https://tanstack.com/router/latest/docs/guide/custom-link.md
References an example demonstrating the integration of `createLink` with Material-UI (MUI) components for creating custom, type-safe links within a TanStack Router application.
```APIDOC
## createLink with MUI (Material-UI)
### Description
This section points to an external example showcasing how to use `createLink` with Material-UI (MUI) components. This integration allows for creating custom links that benefit from MUI's styling and component system while maintaining TanStack Router's type safety.
### Method
N/A (This is a component creation example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
Refer to the [example](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) for detailed implementation.
### Response
N/A (This is a component creation example)
```
--------------------------------
### Manual Mutation Reset with router.subscribe
Source: https://tanstack.com/router/latest/docs/guide/data-mutations.md
This example shows how to manually reset mutation states using the `router.subscribe` method and the `onResolved` event, useful for libraries without built-in keying.
```APIDOC
## Using the `router.subscribe` method
### Description
For mutation libraries that do not support a keying mechanism, this approach demonstrates how to manually reset mutation states. It utilizes TanStack Router's `subscribe` method to listen for route changes and clear mutation states when they are no longer needed.
### Method
Not applicable (Client-side logic)
### Endpoint
Not applicable (Client-side logic)
### Parameters
Not applicable
### Request Example
```tsx
const router = createRouter()
const coolMutationCache = createCoolMutationCache()
const unsubscribeFn = router.subscribe('onResolved', () => {
// Reset mutation states when the route changes
coolMutationCache.clear()
})
// To unsubscribe later:
unsubscribeFn()
```
### Response
Not applicable (Client-side logic)
```
--------------------------------
### Initialize TanStack Router in Solid
Source: https://tanstack.com/router/latest/docs/installation/manual.md
Sets up the root route, child routes, and router instance, then renders the application to the DOM.
```tsx
/* @refresh reload */
import { render } from 'solid-js/web'
import {
Outlet,
RouterProvider,
Link,
createRouter,
createRoute,
createRootRoute,
} from '@tanstack/solid-router'
import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools'
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)
```
--------------------------------
### Paraglide JS Vite Plugin Setup
Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md
Shows how to integrate the Paraglide JS Vite plugin into your project for type-safe translations. This involves importing the plugin and configuring the project and output directory.
```bash
npx @inlang/paraglide-js@latest init
```
```ts
import { paraglideVitePlugin } from '@inlang/paraglide-js'
paraglideVitePlugin({
project: './project.inlang',
outdir: './app/paraglide',
})
```
--------------------------------
### Creating a Root Route Instance with TanStack Router
Source: https://tanstack.com/router/latest/docs/api/router/RootRouteClass.md
This example demonstrates how to instantiate the deprecated RootRoute class to create the root of a route tree. It imports necessary components from '@tanstack/react-router', defines the root route with a basic component, and then adds child routes to form the complete route tree, which is finally used to initialize the router.
```tsx
import { RootRoute, createRouter, Outlet } from '@tanstack/react-router'
const rootRoute = new RootRoute({
component: () => ,
// ... root route options
})
const routeTree = rootRoute.addChildren([
// ... other routes
])
const router = createRouter({
routeTree,
})
```
--------------------------------
### Recommended Legacy Config Setup for ESLint
Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md
Configure ESLint using the legacy .eslintrc format to enable all recommended rules from the TanStack Router ESLint plugin. This is suitable for projects not yet migrated to flat config.
```json
{
"extends": ["plugin:@tanstack/eslint-plugin-router/recommended"]
}
```
--------------------------------
### Custom Flat Config Setup for ESLint
Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md
Manually configure ESLint with the TanStack Router plugin and specify individual rules. This allows for fine-grained control over which rules are enabled.
```javascript
import pluginRouter from '@tanstack/eslint-plugin-router'
export default [
{
plugins: {
'@tanstack/router': pluginRouter,
},
rules: {
'@tanstack/router/create-route-property-order': 'error',
},
},
// Any other config...
]
```
--------------------------------
### Using the Await component with deferred data
Source: https://tanstack.com/router/latest/docs/api/router/awaitComponent.md
This example demonstrates how to use the Await component to handle a deferred promise from a loader. It takes a promise prop and a render function that receives the resolved data.
```tsx
import { Await } from '@tanstack/react-router'
function Component() {
const { deferredPromise } = route.useLoaderData()
return (
{(data) =>
{JSON.stringify(data)}
}
)
}
```
--------------------------------
### Define Route Prefixes
Source: https://tanstack.com/router/latest/docs/guide/path-params.md
Matches URL segments starting with a static prefix followed by a dynamic parameter.
```tsx
export const Route = createFileRoute('/posts/post-{$postId}')({
component: PostComponent,
})
function PostComponent() {
const { postId } = Route.useParams()
// postId will be the value after 'post-'
return
Post ID: {postId}
}
```
```tsx
export const Route = createFileRoute('/posts/post-{$postId}')({
component: PostComponent,
})
function PostComponent() {
const params = Route.useParams()
// postId will be the value after 'post-'
return
Post ID: {params().postId}
}
```
--------------------------------
### Custom Legacy Config Setup for ESLint
Source: https://tanstack.com/router/latest/docs/eslint/eslint-plugin-router.md
Manually configure ESLint with the TanStack Router plugin in the legacy .eslintrc format, specifying individual rules. This provides flexibility in rule selection.
```json
{
"plugins": ["@tanstack/eslint-plugin-router"],
"rules": {
"@tanstack/router/create-route-property-order": "error"
}
}
```
--------------------------------
### Scaffold a new project with CLI
Source: https://tanstack.com/router/latest/docs/quick-start.md
Use the TanStack CLI to initialize a new router-only project for React or Solid.
```bash
@tanstack/cli create --router-only
```
```bash
@tanstack/cli create --router-only --framework solid
```
--------------------------------
### Define Route with Type-Safe Redirect (TypeScript)
Source: https://tanstack.com/router/latest/docs/api/router/RouteType.md
This example demonstrates how to define a route using `createFileRoute` and implement a type-safe redirect using `Route.redirect`. It shows how to conditionally redirect users based on context, ensuring type safety for relative paths.
```typescript
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard/settings')({
beforeLoad: ({ context }) => {
if (!context.user) {
// Type-safe redirect - 'from' is automatically '/dashboard/settings'
throw Route.redirect({
to: '../login', // Relative path to sibling route
})
}
},
})
```
--------------------------------
### Basic useBlocker Hook Usage
Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md
This example demonstrates the basic usage of the useBlocker hook. It blocks navigation when the 'formIsDirty' state is true. No custom UI or resolver is used, relying on the default behavior.
```tsx
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
useBlocker({
shouldBlockFn: () => formIsDirty,
})
// ...
}
```
--------------------------------
### Declarative Route Masking with routeMasks
Source: https://tanstack.com/router/latest/docs/guide/route-masking.md
Example of configuring route masks declaratively using the `routeMasks` option in the `createRouter` function.
```APIDOC
## PUT /api/users/{userId}
### Description
Updates an existing user's information.
### Method
PUT
### Endpoint
/api/users/{userId}
### Parameters
#### Path Parameters
- **userId** (string) - Required - The unique identifier of the user to update.
#### Request Body
- **username** (string) - Optional - The updated username.
- **email** (string) - Optional - The updated email address.
### Request Example
```json
{
"email": "john.doe.updated@example.com"
}
```
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the user.
- **username** (string) - The updated username.
- **email** (string) - The updated email address.
- **updatedAt** (string) - The timestamp when the user was last updated.
#### Response Example
```json
{
"id": "user-12345",
"username": "johndoe",
"email": "john.doe.updated@example.com",
"updatedAt": "2023-10-27T11:30:00Z"
}
```
```
--------------------------------
### Integrate Chakra UI Link with createLink
Source: https://tanstack.com/router/latest/docs/guide/custom-link.md
Example of wrapping a Chakra UI Link component to apply custom styles and default preloading behavior.
```tsx
import * as React from 'react'
import { createLink, LinkComponent } from '@tanstack/react-router'
import { Link } from '@chakra-ui/react'
interface ChakraLinkProps extends Omit, 'href'> {}
const ChakraLinkComponent = React.forwardRef((props, ref) => {
return
})
const CreatedLinkComponent = createLink(ChakraLinkComponent)
export const CustomLink: LinkComponent = (props) => {
return (
)
}
```
--------------------------------
### createLink with Chakra UI
Source: https://tanstack.com/router/latest/docs/guide/custom-link.md
Provides an example of creating a custom Link component using `createLink` that integrates with Chakra UI components, allowing for Chakra's styling props and theming.
```APIDOC
## createLink with Chakra UI
### Description
This example demonstrates how to create a custom `Link` component that integrates with Chakra UI. By using `createLink`, you can apply Chakra UI's styling props and theme customizations to your router links while maintaining type safety.
### Method
N/A (This is a component creation example)
### Endpoint
N/A
### Parameters
N/A
### Request Example
```tsx
import * as React from 'react';
import { createLink, LinkComponent } from '@tanstack/react-router';
import { Link } from '@chakra-ui/react';
interface ChakraLinkProps extends Omit<
React.ComponentPropsWithoutRef,
'href'
> {
// Add any additional props you want to pass to the link
}
const ChakraLinkComponent = React.forwardRef<
HTMLAnchorElement,
ChakraLinkProps
>((props, ref) => {
return ;
});
const CreatedLinkComponent = createLink(ChakraLinkComponent);
export const CustomLink: LinkComponent = (
props,
) => {
return (
);
}
```
### Response
N/A (This is a component creation example)
```
--------------------------------
### Accessing a Route Match
Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md
Example of how to use the `useMatch` hook to access a specific route match based on its ID.
```APIDOC
## Example: Accessing a route match
### Description
This example demonstrates how to use the `useMatch` hook to get the `RouteMatch` object for a specific route, like `/posts/$postId`.
### Code
```tsx
import { useMatch } from '@tanstack/react-router'
function Component() {
const match = useMatch({ from: '/posts/$postId' })
// match is a strict RouteMatch object
// ...
}
```
```
--------------------------------
### Retain All Search Params Example
Source: https://tanstack.com/router/latest/docs/api/router/retainSearchParamsFunction.md
Illustrates using retainSearchParams with `true` to retain all search parameters in a file route.
```APIDOC
## retainSearchParams Middleware (Retain All)
### Description
This example shows how to use `retainSearchParams(true)` to ensure all existing search parameters are carried over during navigation within a file route.
### Method
Configuration within `createFileRoute`'s `search.middlewares` property.
### Endpoint
N/A (Middleware configuration)
### Parameters
- **retainSearchParams** (`true`) - Required - When set to `true`, all search parameters will be retained.
### Request Example
```tsx
import { z } from 'zod'
import { createFileRoute, retainSearchParams } from '@tanstack/react-router'
const searchSchema = z.object({
one: z.string().optional(),
two: z.string().optional(),
})
export const Route = createFileRoute('/')({
validateSearch: searchSchema,
search: {
middlewares: [
retainSearchParams(true) // Retains all search params
],
},
})
```
### Response
N/A (Middleware configuration)
#### Response Example
N/A
```
--------------------------------
### Realistic Data Loading with TanStack Query (React)
Source: https://tanstack.com/router/latest/docs/guide/external-data-loading.md
A more practical example demonstrating data loading using TanStack Query with TanStack Router. It utilizes `queryClient.ensureQueryData` in the loader to prefetch data and `useSuspenseQuery` in the component to consume it, ensuring data is available upon render.
```tsx
const postsQueryOptions = queryOptions({
queryKey: ['posts'],
queryFn: () => fetchPosts(),
})
export const Route = createFileRoute('/posts')({
// Use the `loader` option to ensure that the data is loaded
loader: () => queryClient.ensureQueryData(postsQueryOptions),
component: () => {
// Read the data from the cache and subscribe to updates
const {
data: { posts },
} = useSuspenseQuery(postsQueryOptions)
return (
{posts.map((post) => (
))}
)
},
})
```
--------------------------------
### Imperative Route Masking with Link
Source: https://tanstack.com/router/latest/docs/guide/route-masking.md
Example of using the `mask` option with the `` component to mask a route.
```APIDOC
## POST /api/users
### Description
Creates a new user in the system.
### Method
POST
### Endpoint
/api/users
### Parameters
#### Request Body
- **username** (string) - Required - The username for the new user.
- **email** (string) - Required - The email address for the new user.
- **password** (string) - Required - The password for the new user.
### Request Example
```json
{
"username": "johndoe",
"email": "john.doe@example.com",
"password": "securepassword123"
}
```
### Response
#### Success Response (201)
- **id** (string) - The unique identifier for the newly created user.
- **username** (string) - The username of the created user.
- **email** (string) - The email address of the created user.
#### Response Example
```json
{
"id": "user-12345",
"username": "johndoe",
"email": "john.doe@example.com"
}
```
```
--------------------------------
### Imperative Route Masking with navigate()
Source: https://tanstack.com/router/latest/docs/guide/route-masking.md
Example of using the `mask` option with the `navigate()` API function to mask a route.
```APIDOC
## GET /api/users/{userId}
### Description
Retrieves details for a specific user.
### Method
GET
### Endpoint
/api/users/{userId}
### Parameters
#### Path Parameters
- **userId** (string) - Required - The unique identifier of the user to retrieve.
### Response
#### Success Response (200)
- **id** (string) - The unique identifier for the user.
- **username** (string) - The username of the user.
- **email** (string) - The email address of the user.
- **createdAt** (string) - The timestamp when the user was created.
#### Response Example
```json
{
"id": "user-12345",
"username": "johndoe",
"email": "john.doe@example.com",
"createdAt": "2023-10-27T10:00:00Z"
}
```
```
--------------------------------
### Creating a Root Route with Context - TypeScript/React
Source: https://tanstack.com/router/latest/docs/api/router/createRootRouteWithContextFunction.md
This example demonstrates how to use createRootRouteWithContext to define a root route that requires a specific context type (MyRouterContext). It shows the import statements, context interface definition, route creation, and router instantiation with the provided context.
```tsx
import {
createRootRouteWithContext,
createRouter,
} from '@tanstack/react-router'
import { QueryClient } from '@tanstack/react-query'
interface MyRouterContext {
queryClient: QueryClient
}
const rootRoute = createRootRouteWithContext()({
component: () => ,
// ... root route options
})
const routeTree = rootRoute.addChildren([
// ... other routes
])
const queryClient = new QueryClient()
const router = createRouter({
routeTree,
context: {
queryClient,
},
})
```
--------------------------------
### Render Client-Only Components with TanStack Router
Source: https://tanstack.com/router/latest/docs/api/router/clientOnlyComponent.md
This example demonstrates how to use the ClientOnly component to wrap a component that would otherwise cause hydration errors. It utilizes the fallback prop to provide a placeholder while the main component loads.
```tsx
import { ClientOnly, createFileRoute } from '@tanstack/react-router'
import { Charts, FallbackCharts } from './charts-that-break-server-side-rendering'
export const Route = createFileRoute('/dashboard')({
component: Dashboard,
})
function Dashboard() {
return (
Dashboard
}>
)
}
```
--------------------------------
### useBlocker with Conditional Path Blocking
Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md
This example demonstrates conditional blocking using the 'shouldBlockFn'. Navigation is blocked unless the next path includes '/step/'. It also utilizes 'withResolver: true' for custom UI confirmation.
```tsx
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const { proceed, reset, status } = useBlocker({
shouldBlockFn: ({ next }) => {
return !next.pathname.includes('step/')
},
withResolver: true,
})
// ...
return (
<>
{/* ... */}
{status === 'blocked' && (
Are you sure you want to leave?
)}
>
)
}
```
--------------------------------
### Define and Implement a Lazy Route
Source: https://tanstack.com/router/latest/docs/api/router/createLazyRouteFunction.md
This example demonstrates how to define a lazy route in a separate file using createLazyRoute and then integrate it into the main route tree using the lazy method.
```tsx
// src/route-pages/index.tsx
import { createLazyRoute } from '@tanstack/react-router'
export const Route = createLazyRoute('/')({
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return
{data}
}
// src/routeTree.tsx
import {
createRootRouteWithContext,
createRoute,
Outlet,
} from '@tanstack/react-router'
interface MyRouterContext {
foo: string
}
const rootRoute = createRootRouteWithContext()({
component: () => ,
})
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
}).lazy(() => import('./route-pages/index').then((d) => d.Route))
export const routeTree = rootRoute.addChildren([indexRoute])
```
--------------------------------
### Implement HeadContent in Full-Stack Applications
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
Render the HeadContent component within the head tag of your root layout for full-stack applications using TanStack Start.
```tsx
import { HeadContent } from '@tanstack/react-router'
export const Route = createRootRoute({
component: () => (
),
})
```
```tsx
import { HeadContent } from '@tanstack/solid-router'
export const Route = createRootRoute({
component: () => (
),
})
```
--------------------------------
### Create a file-based route using FileRoute
Source: https://tanstack.com/router/latest/docs/api/router/FileRouteClass.md
Demonstrates how to instantiate a FileRoute and configure it with a loader and a component. The instance must be exported as 'Route' for the TanStack Router CLI tools to generate the route tree correctly.
```tsx
import { FileRoute } from '@tanstack/react-router'
export const Route = new FileRoute('/').createRoute({
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return
{data}
}
```
--------------------------------
### Register Router Instance with TanStack Router
Source: https://tanstack.com/router/latest/docs/api/router/RegisterType.md
This example shows how to register a router instance with TanStack Router using declaration merging. It adds the type of a created router to the `Register` interface, enabling enhanced type safety.
```typescript
const router = createRouter({
// ...
})
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
```
--------------------------------
### Initialize TanStack Router in React
Source: https://tanstack.com/router/latest/docs/api/router/createRouterFunction.md
Demonstrates how to instantiate a router using createRouter with a route tree and default configuration, then providing it to the application via RouterProvider.
```tsx
import { createRouter, RouterProvider } from '@tanstack/react-router';
import { routeTree } from './routeTree.gen';
const router = createRouter({
routeTree,
defaultPreload: 'intent',
});
export default function App() {
return ;
}
```
--------------------------------
### Configure Route Masking with createRouteMask
Source: https://tanstack.com/router/latest/docs/api/router/createRouteMaskFunction.md
This example demonstrates how to define a route mask that maps a modal route to a standard photo URL. The resulting mask is then integrated into the router instance via the routeMasks option.
```tsx
import { createRouteMask, createRouter } from '@tanstack/react-router';
const photoModalToPhotoMask = createRouteMask({
routeTree,
from: '/photos/$photoId/modal',
to: '/photos/$photoId',
params: true,
});
// Set up a Router instance
const router = createRouter({
routeTree,
routeMasks: [photoModalToPhotoMask],
});
```
--------------------------------
### Create a Standard Root Route (Solid)
Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md
Initialize the root route for a Solid application using `createRootRoute` from `@tanstack/solid-router`.
```tsx
// Standard root route
import { createRootRoute } from '@tanstack/solid-router'
const rootRoute = createRootRoute()
```
--------------------------------
### Configure Vite Plugin for TanStack Router
Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md
Install the TanStack Router Vite plugin and add it to your vite.config.js file to enable automatic route watching and updates.
```sh
npm install -D @tanstack/router-plugin
```
```javascript
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
export default defineConfig({
// ...
plugins: [tanstackRouter(), react()],
})
```
--------------------------------
### Retaining all search parameters with retainSearchParams
Source: https://tanstack.com/router/latest/docs/api/router/retainSearchParamsFunction.md
This example shows how to configure retainSearchParams to persist all search parameters by passing the boolean value true within a file route.
```tsx
import { z } from 'zod'
import { createFileRoute, retainSearchParams } from '@tanstack/react-router'
const searchSchema = z.object({
one: z.string().optional(),
two: z.string().optional(),
})
export const Route = createFileRoute('/')({
validateSearch: searchSchema,
search: {
middlewares: [retainSearchParams(true)],
},
})
```
--------------------------------
### Implement basic navigation blocking with useBlocker
Source: https://tanstack.com/router/latest/docs/guide/navigation-blocking.md
Use the useBlocker hook to conditionally prevent navigation when a form is in a dirty state. This example shows how to trigger a confirmation dialog before allowing the user to leave.
```tsx
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
useBlocker({
shouldBlockFn: () => {
if (!formIsDirty) return false
const shouldLeave = confirm('Are you sure you want to leave?')
return !shouldLeave
},
})
}
```
```tsx
import { useBlocker } from '@tanstack/solid-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = createSignal(false)
useBlocker({
shouldBlockFn: () => {
if (!formIsDirty()) return false
const shouldLeave = confirm('Are you sure you want to leave?')
return !shouldLeave
},
})
}
```
--------------------------------
### React Authentication using Context and Hooks
Source: https://tanstack.com/router/latest/docs/guide/authenticated-routes.md
This example demonstrates how to integrate authentication state managed by React context and hooks into TanStack Router. It involves defining a router context, passing the authentication state down via the RouterProvider, and using it to protect routes.
```tsx
import { createRootRouteWithContext, Outlet } from '@tanstack/react-router';
interface MyRouterContext {
auth: AuthState
}
export const Route = createRootRouteWithContext()({
component: () => ,
});
```
```tsx
import { createRouter } from '@tanstack/react-router';
import { routeTree } from './routeTree.gen';
export const router = createRouter({
routeTree,
context: {
auth: undefined!,
},
});
```
```tsx
import { RouterProvider } from '@tanstack/react-router';
import { AuthProvider, useAuth } from './auth';
import { router } from './router';
function InnerApp() {
const auth = useAuth();
return ;
}
function App() {
return (
);
}
```
--------------------------------
### Pass Initial Router Context (Solid)
Source: https://tanstack.com/router/latest/docs/guide/router-context.md
Initialize the router with a context object. This context is accessible by all routes and serves for dependency injection.
```tsx
import { createRouter } from '@tanstack/solid-router'
// Use the routerContext you created to create your router
const router = createRouter({
routeTree,
context: {
user: {
id: '123',
name: 'John Doe',
},
},
})
```
--------------------------------
### Link Component with Locale Rewrite
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
The Link component automatically applies output rewrites. This example shows how a configured locale rewrite adds a prefix to the href.
```tsx
// With locale rewrite configured (adds /en prefix)
About
// Renders: About
```
--------------------------------
### Configure Esbuild for Solid with TanStack Router
Source: https://tanstack.com/router/latest/docs/installation/with-esbuild.md
Integrate the tanstackRouter plugin into your Esbuild build process for Solid applications. This setup includes the solidPlugin and enables auto code splitting.
```javascript
import * as esbuild from 'esbuild'
import { solidPlugin } from 'esbuild-plugin-solid'
import { tanstackRouter } from '@tanstack/router-plugin/esbuild'
const isDev = process.argv.includes('--dev')
const ctx = await esbuild.context({
entryPoints: ['src/main.tsx'],
outfile: 'dist/main.js',
minify: !isDev,
bundle: true,
format: 'esm',
target: ['esnext'],
sourcemap: true,
plugins: [
solidPlugin(),
tanstackRouter({ target: 'solid', autoCodeSplitting: true }),
],
})
if (isDev) {
await ctx.watch()
const { host, port } = await ctx.serve({ servedir: '.', port: 3005 })
console.log(`Server running at http://${host || 'localhost'}:${port}`)
} else {
await ctx.rebuild()
await ctx.dispose()
}
```
--------------------------------
### Create Route Instance with Options - React (TypeScript)
Source: https://tanstack.com/router/latest/docs/api/router/createRouteFunction.md
This example demonstrates how to use the createRoute function to create a root route instance in a React application using TypeScript. It configures the parent route, path, loader, and component for the index route.
```tsx
import { createRoute } from '@tanstack/react-router'
import { rootRoute } from './__root'
const Route = createRoute({
getParentRoute: () => rootRoute,
path: '/',
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return
{data}
}
```
--------------------------------
### Basic Link Navigation with Parameters
Source: https://tanstack.com/router/latest/docs/api/router/linkComponent.md
Demonstrates how to use the Link component to navigate to a route with dynamic path parameters and updated search parameters. It shows the integration within a React component.
```tsx
import { Link } from '@tanstack/react-router'
function Component() {
return (
({ ...prev, foo: 'bar' })}
>
Click me
)
}
```
--------------------------------
### Create Root Route with Context (React)
Source: https://tanstack.com/router/latest/docs/api/router/rootRouteWithContextFunction.md
Demonstrates how to use the deprecated `rootRouteWithContext` function to create a root route that requires a specific context type (e.g., QueryClient) when initializing the router. This setup is useful for providing shared resources to your application's routes.
```tsx
import { rootRouteWithContext, createRouter } from '@tanstack/react-router'
import { QueryClient } from '@tanstack/react-query'
interface MyRouterContext {
queryClient: QueryClient
}
const rootRoute = rootRouteWithContext()({
component: () => ,
// ... root route options
})
const routeTree = rootRoute.addChildren([
// ... other routes
])
const queryClient = new QueryClient()
const router = createRouter({
routeTree,
context: {
queryClient,
},
})
```
--------------------------------
### CatchNotFound Component Usage Example
Source: https://tanstack.com/router/latest/docs/api/router/catchNotFoundComponent.md
Demonstrates how to use the CatchNotFound component to wrap a component that might throw a not-found error. It shows how to provide a fallback component and an optional error handling callback.
```tsx
import { CatchNotFound } from '@tanstack/react-router'
function Component() {
return (
Not found error! {JSON.stringify(error)}
}
>
)
}
```
--------------------------------
### Retrieve child matches with useChildMatches
Source: https://tanstack.com/router/latest/docs/api/router/useChildMatchesHook.md
This example demonstrates the basic usage of the useChildMatches hook to access an array of child route matches within a React component.
```tsx
import { useChildMatches } from '@tanstack/react-router';
function Component() {
const childMatches = useChildMatches();
// Access child route matches here
}
```
--------------------------------
### Accessing Search Parameters with useSearch
Source: https://tanstack.com/router/latest/docs/api/router/useSearchHook.md
Demonstrates how to retrieve search parameters using the useSearch hook. It includes examples for specific route targeting, using the select option for data transformation, and enabling loose typing.
```tsx
import { useSearch } from '@tanstack/react-router'
function Component() {
const search = useSearch({ from: '/posts/$postId' })
const selected = useSearch({
from: '/posts/$postId',
select: (search) => search.postView,
})
const looseSearch = useSearch({ strict: false })
}
```
--------------------------------
### Create Router with Context in Solid
Source: https://tanstack.com/router/latest/docs/guide/data-loading.md
Instantiate the router using `createRouter`, providing the `routeTree` and fulfilling the type requirements of the `routerContext` by supplying necessary functions like `fetchPosts`.
```tsx
import { routeTree } from './routeTree.gen'
// Use your routerContext to create a new router
// This will require that you fullfil the type requirements of the routerContext
const router = createRouter({
routeTree,
context: {
// Supply the fetchPosts function to the router context
fetchPosts,
},
})
```
--------------------------------
### Main Application Entry Point with TanStack Router
Source: https://tanstack.com/router/latest/docs/installation/manual.md
Sets up the main entry point for a React application using TanStack Router. It creates a router instance from the generated route tree and renders the application with the RouterProvider.
```typescript
import { StrictMode } from 'react'
import ReactDOM from 'react-dom/client'
import { RouterProvider, createRouter } from '@tanstack/react-router'
// Import the generated route tree
import { routeTree } from './routeTree.gen'
// Create a new router instance
const router = createRouter({ routeTree })
// Register the router instance for type safety
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
// Render the app
const rootElement = document.getElementById('root')!
if (!rootElement.innerHTML) {
const root = ReactDOM.createRoot(rootElement)
root.render(
,
)
}
```
--------------------------------
### Conditionally render a back button using useCanGoBack
Source: https://tanstack.com/router/latest/docs/api/router/useCanGoBack.md
This example demonstrates how to use the useCanGoBack hook to check if navigation history exists and conditionally render a button that triggers the router's history.back() method.
```tsx
import { useRouter, useCanGoBack } from '@tanstack/react-router'
function Component() {
const router = useRouter()
const canGoBack = useCanGoBack()
return (
{canGoBack ? (
) : null}
)
}
```
--------------------------------
### useBlocker Without Resolver
Source: https://tanstack.com/router/latest/docs/api/router/useBlockerHook.md
This example shows the useBlocker hook without using the 'withResolver' option. The 'shouldBlockFn' directly uses the browser's 'confirm' dialog to ask the user if they want to leave.
```tsx
import { useBlocker } from '@tanstack/react-router'
function MyComponent() {
const [formIsDirty, setFormIsDirty] = useState(false)
useBlocker({
shouldBlockFn: ({ next }) => {
if (next.pathname.includes('step/')) {
return false
}
const shouldLeave = confirm('Are you sure you want to leave?')
return !shouldLeave
},
})
// ...
}
```
--------------------------------
### Link Component with Hostname Rewrite
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
When an output rewrite changes the hostname, the Link component renders a standard anchor tag for hard navigation. This example shows a rewrite for '/admin' paths to 'admin.example.com'.
```tsx
// Rewrite that changes hostname for /admin paths
const router = createRouter({
routeTree,
rewrite: {
output: ({ url }) => {
if (url.pathname.startsWith('/admin')) {
url.hostname = 'admin.example.com'
url.pathname = url.pathname.replace(/^\/admin/, '') || '/'
}
return url
},
},
})
// This link will be a hard navigation (full page load)
Admin Dashboard
// Renders: Admin Dashboard
```
--------------------------------
### Naive Data Loading with Route Loader (React)
Source: https://tanstack.com/router/latest/docs/guide/external-data-loading.md
An illustrative example of using a route's `loader` option to seed a cache with data. This approach is flawed but demonstrates the concept of preloading data before the component renders. It directly manipulates a global cache variable.
```tsx
let postsCache = []
export const Route = createFileRoute('/posts')({
loader: async () => {
postsCache = await fetchPosts()
},
component: () => {
return (
{postsCache.map((post) => (
))}
)
},
})
```
--------------------------------
### Imperative Navigation with useNavigate
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Use the `useNavigate` hook to get a `navigate` function for imperative navigation, typically from side effects after an async action. Specify the `from` route option to reduce potential errors.
```tsx
function Component() {
const navigate = useNavigate({ from: '/posts/$postId' })
const handleSubmit = async (e: FrameworkFormEvent) => {
e.preventDefault()
const response = await fetch('/posts', {
method: 'POST',
body: JSON.stringify({ title: 'My First Post' }),
})
const { id: postId } = await response.json()
if (response.ok) {
navigate({ to: '/posts/$postId', params: { postId } })
}
}
}
```
--------------------------------
### Initialize Router Instance
Source: https://tanstack.com/router/latest/docs/guide/creating-a-router.md
Creates a new Router instance using the framework-specific package. This instance manages the route tree and global router configuration.
```tsx
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
// ...
})
```
```tsx
import { createRouter } from '@tanstack/solid-router'
const router = createRouter({
// ...
})
```
--------------------------------
### Accessing Route Loader Data with useLoaderData
Source: https://tanstack.com/router/latest/docs/api/router/useLoaderDataHook.md
This example demonstrates how to use the useLoaderData hook to retrieve data from a specific route match. By providing the 'from' option, the hook ensures type safety for the returned loader data.
```tsx
import { useLoaderData } from '@tanstack/react-router'
function Component() {
const loaderData = useLoaderData({ from: '/posts/$postId' })
// loaderData is typed based on the route definition
}
```
--------------------------------
### Language Switching Link Component
Source: https://tanstack.com/router/latest/docs/guide/internationalization-i18n.md
Provides an example of a Link component that toggles the locale parameter between 'en' and 'fr'. This allows users to switch languages dynamically within the application.
```tsx
({
...prev,
locale: prev.locale === 'en' ? undefined : 'fr',
})}>
Français
```
--------------------------------
### React Code-Based Route Configuration
Source: https://tanstack.com/router/latest/docs/installation/manual.md
Configures routes using code for a React application, including a root layout, index, and about routes. This example uses code-based generation and requires a root element with id 'app'.
```tsx
import { StrictMode } from 'react'
import ReactDOM from 'react-dom/client'
import {
Outlet,
RouterProvider,
Link,
createRouter,
createRoute,
createRootRoute,
} from '@tanstack/react-router'
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools'
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(
,
)
}
```
--------------------------------
### Retaining specific search parameters with retainSearchParams
Source: https://tanstack.com/router/latest/docs/api/router/retainSearchParamsFunction.md
This example demonstrates how to use retainSearchParams with an array of keys to persist specific search parameters defined in a Zod schema within a root route.
```tsx
import { z } from 'zod'
import { createRootRoute, retainSearchParams } from '@tanstack/react-router'
const searchSchema = z.object({
rootValue: z.string().optional(),
})
export const Route = createRootRoute({
validateSearch: searchSchema,
search: {
middlewares: [retainSearchParams(['rootValue'])],
},
})
```
--------------------------------
### Set Default Preload Strategy to Intent
Source: https://tanstack.com/router/latest/docs/guide/preloading.md
Configures the router to use the 'intent' preloading strategy by default for all links. This strategy preloads route dependencies based on hover and touch start events.
```tsx
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
// ...
defaultPreload: 'intent',
})
```
```tsx
import { createRouter } from '@tanstack/solid-router'
const router = createRouter({
// ...
defaultPreload: 'intent',
})
```
--------------------------------
### Implementing CatchBoundary with Error Handling and Reset
Source: https://tanstack.com/router/latest/docs/api/router/catchBoundaryComponent.md
This example demonstrates how to use the CatchBoundary component to catch errors from its children. It includes an `onCatch` callback to log the error and a `getResetKey` function to enable state resetting when the key changes. The component renders its children when there are no errors and the `errorComponent` when an error occurs.
```tsx
import { CatchBoundary } from '@tanstack/react-router'
function Component() {
return (
'reset'}
onCatch={(error) => console.error(error)}
>
My Component
)
}
```
--------------------------------
### Configure Router Context for React and Solid
Source: https://tanstack.com/router/latest/docs/guide/router-context.md
Sets up a typed router context for integrating external libraries like QueryClient.
```tsx
import {
createRootRouteWithContext,
createRouter,
} from '@tanstack/react-router'
interface MyRouterContext {
queryClient: QueryClient
}
const rootRoute = createRootRouteWithContext()({
component: App,
})
const queryClient = new QueryClient()
const router = createRouter({
routeTree: rootRoute,
context: {
queryClient,
},
})
```
```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,
},
})
```
--------------------------------
### Solid Router Initialization
Source: https://tanstack.com/router/latest/docs/installation/manual.md
Initializes and renders the TanStack Router for a Solid application. Ensure your HTML has a root element with id 'root'.
```tsx
/* @refresh reload */
import { render } from 'solid-js/web'
import { RouterProvider, createRouter } from '@tanstack/solid-router'
// Import the generated route tree
import { routeTree } from './routeTree.gen'
// Create a new router instance
const router = createRouter({ routeTree })
// Register the router instance for type safety
declare module '@tanstack/solid-router' {
interface Register {
router: typeof router
}
}
// Render the app
const rootElement = document.getElementById('root')!
render(() => , rootElement)
```
--------------------------------
### Initialize Router with Placeholder Context
Source: https://tanstack.com/router/latest/docs/guide/router-context.md
Initializes the router with a placeholder for context values that will be provided in React-land.
```tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
export const router = createRouter({
routeTree,
context: {
networkStrength: undefined!, // We'll set this in React-land
},
})
```
--------------------------------
### Transform Search Params with Custom Middleware
Source: https://tanstack.com/router/latest/docs/guide/search-params.md
Define custom search middlewares in the `search.middlewares` array to transform search parameters before links are generated or during navigation. This example adds `rootValue` to the search params if it exists.
```tsx
import { z } from 'zod'
import { zodValidator } from '@tanstack/zod-adapter'
const searchSchema = z.object({
rootValue: z.string().optional(),
})
export const Route = createRootRoute({
validateSearch: zodValidator(searchSchema),
search: {
middlewares: [
({ search, next }) => {
const result = next(search)
return {
rootValue: search.rootValue,
...result,
}
},
],
},
})
```
--------------------------------
### SSR Dehydration/Hydration with TanStack Query
Source: https://tanstack.com/router/latest/docs/guide/external-data-loading.md
This example demonstrates how to configure TanStack Router with `dehydrate` and `hydrate` callbacks to serialize and deserialize a `QueryClient`'s state for SSR. This ensures that data fetched on the server is available on the client, improving initial load performance.
```tsx
import { QueryClient, QueryClientProvider, dehydrate, hydrate } from '@tanstack/query-core'
import { createRouter } from '@tanstack/react-router'
// Assuming routeTree is defined elsewhere
// import { routeTree } from './routeTree'
export function createRouter() {
// Make sure you create your loader client or similar data
// stores inside of your `createRouter` function. This ensures
// that your data stores are unique to each request and
// always present on both server and client.
const queryClient = new QueryClient()
return createRouter({
routeTree,
// Optionally provide your loaderClient to the router context for
// convenience (you can provide anything you want to the router
// context!)
context: {
queryClient,
},
// On the server, dehydrate the loader client so the router
// can serialize it and send it to the client for us
dehydrate: () => {
return {
queryClientState: dehydrate(queryClient),
}
},
// On the client, hydrate the loader client with the data
// we dehydrated on the server
hydrate: (dehydrated) => {
hydrate(queryClient, dehydrated.queryClientState)
},
// Optionally, we can use `Wrap` to wrap our router in the loader client provider
Wrap: ({ children }) => {
return (
{children}
)
},
})
}
```
--------------------------------
### Using useNavigate Hook for Navigation in React
Source: https://tanstack.com/router/latest/docs/api/router/useNavigateHook.md
Demonstrates how to use the useNavigate hook to get a navigate function for programmatic navigation. The navigate function can be called with options to change the search parameters, pathname, hash, or state, allowing for flexible route updates.
```tsx
import { useNavigate } from '@tanstack/react-router'
function PostsPage() {
const navigate = useNavigate({ from: '/posts' })
const handleClick = () => navigate({ search: { page: 2 } })
// ...
}
function Component() {
const navigate = useNavigate()
return (
)
}
```
--------------------------------
### Subscribe to Router Events
Source: https://tanstack.com/router/latest/docs/api/router/RouterEventsType.md
Demonstrates how to initialize a router instance and subscribe to specific lifecycle events using the router.subscribe method.
```typescript
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({ routeTree })
const unsub = router.subscribe('onResolved', (evt) => {
// Handle the resolved event
})
```
--------------------------------
### Manual Scroll Restoration for Window Virtualization (React)
Source: https://tanstack.com/router/latest/docs/guide/scroll-restoration.md
Manually controls scroll restoration for virtualized lists within the entire browser window. It uses `useElementScrollRestoration` to get scroll data and passes it to `useWindowVirtualizer` for initial offset. Dependencies include TanStack Router and TanStack Virtual.
```tsx
function Component() {
const scrollEntry = useElementScrollRestoration({
getElement: () => window,
})
const virtualizer = useWindowVirtualizer({
count: 10000,
estimateSize: () => 100,
initialOffset: scrollEntry?.scrollY,
})
return (
)
}
```
--------------------------------
### Instantiate Router Instance with React
Source: https://tanstack.com/router/latest/docs/api/router/RouterClass.md
Demonstrates how to instantiate a new router instance using the deprecated `Router` class and integrate it with `RouterProvider` in a React application. It configures the router with a route tree and a default preload strategy.
```tsx
import { Router, RouterProvider } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = new Router({
routeTree,
defaultPreload: 'intent',
})
export default function App() {
return
}
```
--------------------------------
### Create a basic custom link component
Source: https://tanstack.com/router/latest/docs/guide/custom-link.md
Demonstrates how to use createLink to wrap a standard anchor element in React and Solid, providing consistent styling and preloading behavior.
```tsx
import * as React from 'react'
import { createLink, LinkComponent } from '@tanstack/react-router'
interface BasicLinkProps extends React.AnchorHTMLAttributes {}
const BasicLinkComponent = React.forwardRef((props, ref) => {
return
})
const CreatedLinkComponent = createLink(BasicLinkComponent)
export const CustomLink: LinkComponent = (props) => {
return
}
```
```tsx
import * as Solid from 'solid-js'
import { createLink, LinkComponent } from '@tanstack/solid-router'
type BasicLinkProps = Solid.JSX.IntrinsicElements['a'] & {}
const BasicLinkComponent: Solid.Component = (props) => (
{props.children}
)
const CreatedLinkComponent = createLink(BasicLinkComponent)
export const CustomLink: LinkComponent = (props) => {
return
}
```
--------------------------------
### Zod v4 Direct Schema Validation
Source: https://tanstack.com/router/latest/docs/guide/search-params.md
For Zod v4, directly use the Zod schema in `validateSearch` without an adapter. This simplifies the setup and maintains type inference.
```tsx
import { z } from 'zod'
const productSearchSchema = z.object({
page: z.number().default(1),
filter: z.string().default(''),
sort: z.enum(['newest', 'oldest', 'price']).default('newest'),
})
export const Route = createFileRoute('/shop/products/')({
// With Zod v4, we can use the schema without the adapter
validateSearch: productSearchSchema,
})
```
--------------------------------
### Create Root Route with Context in Solid
Source: https://tanstack.com/router/latest/docs/guide/data-loading.md
Use `createRootRouteWithContext` to define a root route and provide typed context for your router. Note the double call `()()` which is intentional.
```tsx
import { createRootRouteWithContext } from '@tanstack/solid-router'
// Create a root route using the createRootRouteWithContext<{...}>() function and pass it whatever types you would like to be available in your router context.
export const Route = createRootRouteWithContext<{
fetchPosts: typeof fetchPosts
}>()() // NOTE: the double call is on purpose, since createRootRouteWithContext is a factory ;)
```
--------------------------------
### Accessing Route Context with useRouteContext (React)
Source: https://tanstack.com/router/latest/docs/api/router/useRouteContextHook.md
Demonstrates how to use the useRouteContext hook in React components to retrieve the current route's context. It shows examples of accessing the full context and selecting specific properties using the 'select' option.
```tsx
import { useRouteContext } from '@tanstack/react-router'
function Component() {
const context = useRouteContext({ from: '/posts/$postId' })
// ^ RouteContext
// OR
const selected = useRouteContext({
from: '/posts/$postId',
select: (context) => context.postId,
})
// ^ string
// ...
}
```
--------------------------------
### Immediate Navigation with Navigate Component
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Render the `Navigate` component to navigate immediately when a component mounts. This is useful for client-only redirects.
```tsx
function Component() {
return
}
```
--------------------------------
### ArkType Standard Schema Validation
Source: https://tanstack.com/router/latest/docs/guide/search-params.md
Integrate ArkType schemas directly into `validateSearch` without an adapter, as ArkType implements Standard Schema. Ensure the `arktype` 2.0-rc package is installed.
```tsx
import { type } from 'arktype'
const productSearchSchema = type({
page: 'number = 1',
filter: 'string = ""',
sort: '"newest" | "oldest" | "price" = "newest"',
})
export const Route = createFileRoute('/shop/products/')({
validateSearch: productSearchSchema,
})
```
--------------------------------
### Router Configuration
Source: https://tanstack.com/router/latest/docs/guide/render-optimizations.md
Configuring global router options for performance optimizations.
```APIDOC
## POST createRouter
### Description
Initializes the router instance with global configuration options, including default structural sharing behavior.
### Method
FUNCTION
### Parameters
#### Options
- **routeTree** (RouteTree) - Required - The defined route tree.
- **defaultStructuralSharing** (boolean) - Optional - Globally enables or disables structural sharing for all select hooks.
```
--------------------------------
### Valibot Standard Schema Validation
Source: https://tanstack.com/router/latest/docs/guide/search-params.md
Use Valibot schemas directly in `validateSearch` without an adapter, as Valibot implements Standard Schema. Ensure the `valibot` 1.0 package is installed.
```tsx
import * as v from 'valibot'
const productSearchSchema = v.object({
page: v.optional(v.fallback(v.number(), 1), 1),
filter: v.optional(v.fallback(v.string(), ''), ''),
sort: v.optional(
v.fallback(v.picklist(['newest', 'oldest', 'price']), 'newest'),
'newest',
),
})
export const Route = createFileRoute('/shop/products/')({
validateSearch: productSearchSchema,
})
```
--------------------------------
### Using useAwaited to resolve deferred promises
Source: https://tanstack.com/router/latest/docs/api/router/useAwaitedHook.md
This example demonstrates how to use the useAwaited hook within a React component to await a deferred promise provided by the router's loader data. It ensures the component suspends until the data is available.
```tsx
import { useAwaited } from '@tanstack/react-router'
function Component() {
const { deferredPromise } = route.useLoaderData()
const data = useAwaited({ promise: myDeferredPromise })
// ...
}
```
--------------------------------
### Configure Supabase Environment Variables
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Sets up environment variables for Supabase URL and Anon Key in a `.env` file. These are required for the Supabase client to connect to your project.
```env
VITE_SUPABASE_URL=https://your-project.supabase.co
VITE_SUPABASE_ANON_KEY=your_supabase_anon_key
```
--------------------------------
### Link Component with Intent-Based Preloading
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Demonstrates how to enable automatic route preloading on user intent (hover or touchstart) by passing the `preload='intent'` prop to the Link component.
```tsx
const link = (
Blog Post
)
```
--------------------------------
### Run DOM-Dependent Logic with onRendered (TypeScript/React)
Source: https://tanstack.com/router/latest/docs/guide/router-events.md
This example demonstrates using the 'onRendered' event to execute logic that depends on the DOM. It subscribes to 'onRendered' and calls a function to focus the page heading based on the new route's pathname.
```tsx
const unsubscribe = router.subscribe('onRendered', ({ toLocation }) => {
focusPageHeading(toLocation.pathname)
})
```
--------------------------------
### Default Configuration for Solid Projects
Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md
Default configuration options for TanStack Router CLI when targeting Solid projects.
```json
{
"routesDirectory": "./src/routes",
"generatedRouteTree": "./src/routeTree.gen.ts",
"routeFileIgnorePrefix": "-",
"quoteStyle": "single",
"target": "solid"
}
```
--------------------------------
### Create Lazy File Route Instance - React
Source: https://tanstack.com/router/latest/docs/api/router/createLazyFileRouteFunction.md
Demonstrates how to use the createLazyFileRoute function to define a lazily loaded route component for the root path in a React application using TanStack Router. This setup allows for code splitting and efficient loading of route components.
```tsx
import { createLazyFileRoute } from '@tanstack/react-router'
export const Route = createLazyFileRoute('/')({
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return
{data}
}
```
--------------------------------
### Auth0 Environment Variables
Source: https://tanstack.com/router/latest/docs/how-to/setup-auth-providers.md
Configure your Auth0 domain and client ID in your .env file. These are required for the Auth0Provider.
```env
VITE_AUTH0_DOMAIN=your-auth0-domain.auth0.com
VITE_AUTH0_CLIENT_ID=your_auth0_client_id
```
--------------------------------
### Code-Splitting Data Loaders with lazyFn
Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md
Illustrates how to code-split data loading logic for routes using the Route's loader option and the lazyFn utility. This can reduce bundle size but may impact type-safety.
```tsx
import { lazyFn } from '@tanstack/react-router'
const route = createRoute({
path: '/my-route',
component: MyComponent,
loader: lazyFn(() => import('./loader'), 'loader'),
})
// In another file...
export const loader = async (context: LoaderContext) => {
/// ...
}
```
```tsx
import { lazyFn } from '@tanstack/solid-router'
const route = createRoute({
path: '/my-route',
component: MyComponent,
loader: lazyFn(() => import('./loader'), 'loader'),
})
// In another file...
export const loader = async (context: LoaderContext) => {
/// ...
}
```
--------------------------------
### Programmatic Navigation
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Shows how to perform programmatic navigation using `navigate()` or `router.navigate()`, which also respects URL rewrites.
```APIDOC
## Programmatic Navigation
Programmatic navigation via `navigate()` or `router.navigate()` also respects rewrites:
### Request Example
```tsx
const navigate = useNavigate()
// Navigates to /about internally, displays /en/about in browser
navigate({ to: '/about' })
```
```
--------------------------------
### Manually Preload a Route (React, Solid)
Source: https://tanstack.com/router/latest/docs/guide/preloading.md
Demonstrates how to use the router's `preloadRoute` method to manually preload a specific route. This method accepts navigation options and returns a promise that resolves upon successful preloading. Error handling for preload failures is included.
```tsx
import { useEffect } from 'react'
import { useRouter } from '@tanstack/react-router'
function Component() {
const router = useRouter()
useEffect(() => {
async function preload() {
try {
const matches = await router.preloadRoute({
to: postRoute,
params: { id: 1 },
})
} catch (err) {
// Failed to preload route
}
}
preload()
}, [router])
return
}
```
```tsx
import { createEffect } from 'solid-js'
import { useRouter } from '@tanstack/solid-router'
function Component() {
const router = useRouter()
createEffect(() => {
async function preload() {
try {
const matches = await router.preloadRoute({
to: postRoute,
params: { id: 1 },
})
} catch (err) {
// Failed to preload route
}
}
preload()
})
return
}
```
--------------------------------
### Create Posts Route File
Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md
Defines the '/posts' route with a component and a loader function to fetch posts. Use this for the main posts listing page.
```tsx
// src/routes/posts.tsx
import { createFileRoute, Link, Outlet } from '@tanstack/react-router'
export const Route = createFileRoute('/posts')({
component: Posts,
loader: async () => {
const posts = await fetchPosts()
return {
posts,
}
},
})
function Posts() {
const { posts } = Route.useLoaderData()
return (
)
}
```
--------------------------------
### Handle Validation Errors with Zod
Source: https://tanstack.com/router/latest/docs/guide/search-params.md
Configure `onError` to handle search param validation errors by rendering an `errorComponent`. This example uses Zod's `.default()` to trigger an error when parameters are malformed.
```typescript
import { z } from 'zod'
const productSearchSchema = z.object({
page: z.number().default(1),
filter: z.string().default(''),
sort: z.enum(['newest', 'oldest', 'price']).default('newest'),
})
export const Route = createFileRoute('/shop/products/')({
validateSearch: productSearchSchema,
})
```
--------------------------------
### i18n Locale Prefix URL Rewrite
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Strip locale prefixes from the browser URL on input and add them back on output. This example demonstrates how to handle locale prefixes like '/en/about' by removing 'en' before routing and re-adding it based on the current locale when navigating.
```tsx
const locales = ['en', 'fr', 'es', 'de']
const defaultLocale = 'en'
// Get current locale (from cookie, localStorage, or detection)
function getLocale() {
return localStorage.getItem('locale') || defaultLocale
}
const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => {
// Check if pathname starts with a locale prefix
const segments = url.pathname.split('/').filter(Boolean)
const firstSegment = segments[0]
if (firstSegment && locales.includes(firstSegment)) {
// Strip the locale prefix: /en/about → /about
url.pathname = '/' + segments.slice(1).join('/') || '/'
}
return url
},
output: ({ url }) => {
const locale = getLocale()
// Add locale prefix: /about → /en/about
if (locale !== defaultLocale || true) {
// Always prefix, or conditionally skip default locale
url.pathname = `/${locale}${url.pathname === '/' ? '' : url.pathname}`
}
return url
},
},
})
```
--------------------------------
### Standalone redirect function usage in React Router
Source: https://tanstack.com/router/latest/docs/api/router/redirectFunction.md
Demonstrates how to use the standalone `redirect` function from '@tanstack/react-router' within route loader callbacks. It shows examples of redirecting to internal routes using 'to' and external URLs using 'href', as well as forcing the function to throw the redirect object.
```tsx
import { redirect } from '@tanstack/react-router'
const route = createRoute({
// throwing an internal redirect object using 'to' property
loader: () => {
if (!user) {
throw redirect({
to: '/login',
})
}
},
// throwing an external redirect object using 'href' property
loader: () => {
if (needsExternalAuth) {
throw redirect({
href: 'https://authprovider.com/login',
})
}
},
// or forcing `redirect` to throw itself
loader: () => {
if (!user) {
redirect({
to: '/login',
throw: true,
})
}
},
// ... other route options
})
```
--------------------------------
### Initialize Router Context
Source: https://tanstack.com/router/latest/docs/guide/router-context.md
Provide the initial context object when creating the router instance.
```tsx
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({
routeTree,
context: {
foo: true,
},
})
```
```tsx
import { createRouter } from '@tanstack/solid-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({
routeTree,
context: {
foo: true,
},
})
```
--------------------------------
### Solid: Query-String Library for Search Param Serialization
Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md
Shows how to integrate the 'query-string' library with TanStack Router in SolidJS for robust search parameter parsing and stringification. This ensures consistent query string handling.
```tsx
import { createRouter } from '@tanstack/solid-router'
import qs from 'query-string'
const router = createRouter({
// ...
stringifySearch: stringifySearchWith((value) =>
qs.stringify(value, {
// ...options
}),
),
parseSearch: parseSearchWith((value) =>
qs.parse(value, {
// ...options
}),
),
})
```
--------------------------------
### Throwing NotFoundError in Route Loader
Source: https://tanstack.com/router/latest/docs/api/router/notFoundFunction.md
Demonstrates how to use the notFound function within a route's loader callback to throw a NotFoundError. This can be used to conditionally display a 'not found' component based on data availability or other conditions. The example shows throwing a basic notFound object and another with a specified routeId.
```tsx
import { notFound, createFileRoute, rootRouteId } from '@tanstack/react-router'
const Route = new createFileRoute('/posts/$postId')({
// throwing a not-found object
loader: ({ context: { post } }) => {
if (!post) {
throw notFound()
}
},
// or if you want to show a not-found on the whole page
loader: ({ context: { team } }) => {
if (!team) {
throw notFound({ routeId: rootRouteId })
}
},
// ... other route options
})
```
--------------------------------
### Navigate with Path Params (Function Style)
Source: https://tanstack.com/router/latest/docs/guide/path-params.md
Illustrates navigating to a route with path parameters using a function for the `params` prop. This allows for merging existing params with new ones.
```tsx
function Component() {
return (
({ ...prev, postId: '123' })}>
Post 123
)
}
```
--------------------------------
### Manual Scroll Restoration for Specific Elements (React & Solid)
Source: https://tanstack.com/router/latest/docs/guide/scroll-restoration.md
Manually controls scroll restoration for a specific element, such as a virtualized list container. It requires a unique `scrollRestorationId` and uses the `data-scroll-restoration-id` attribute on the target element. The `useElementScrollRestoration` hook provides scroll data, which is then passed to the virtualizer's `initialOffset`. This example demonstrates implementations in both React and Solid.
```tsx
function Component() {
const scrollRestorationId = 'myVirtualizedContent'
const scrollEntry = useElementScrollRestoration({
id: scrollRestorationId,
})
const virtualizerParentRef = React.useRef(null)
const virtualizer = useVirtualizer({
count: 10000,
getScrollElement: () => virtualizerParentRef.current,
estimateSize: () => 100,
initialOffset: scrollEntry?.scrollY,
})
return (
)
}
```
--------------------------------
### Define Solid Routes with Code
Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md
Use `createRootRoute` and `createRoute` to define your application's route tree in code for Solid. This approach mirrors file-based routing structure but is defined programmatically.
```tsx
import { createRootRoute, createRoute } from '@tanstack/solid-router'
const rootRoute = createRootRoute()
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
})
const aboutRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'about',
})
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts',
})
const postsIndexRoute = createRoute({
getParentRoute: () => postsRoute,
path: '/',
})
const postRoute = createRoute({
getParentRoute: () => postsRoute,
path: '$postId',
})
const postEditorRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts/$postId/edit',
})
const settingsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'settings',
})
const profileRoute = createRoute({
getParentRoute: () => settingsRoute,
path: 'profile',
})
const notificationsRoute = createRoute({
getParentRoute: () => settingsRoute,
path: 'notifications',
})
const pathlessLayoutRoute = createRoute({
getParentRoute: () => rootRoute,
id: 'pathlessLayout',
})
const pathlessLayoutARoute = createRoute({
getParentRoute: () => pathlessLayoutRoute,
path: 'route-a',
})
const pathlessLayoutBRoute = createRoute({
getParentRoute: () => pathlessLayoutRoute,
path: 'route-b',
})
const filesRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'files/$',
})
```
--------------------------------
### Execute Inline Scripts Before Hydration with ScriptOnce
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
ScriptOnce allows for the execution of JavaScript before the framework hydrates. This is ideal for theme detection to avoid flashes of unstyled content.
```tsx
import { ScriptOnce } from '@tanstack/react-router'
const themeScript = `(function() {
try {
const theme = localStorage.getItem('theme') || 'auto';
const resolved = theme === 'auto'
? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
: theme;
document.documentElement.classList.add(resolved);
} catch (e) {}
})();`
function ThemeProvider({ children }) {
return (
<>
{children}
>
)
}
```
```tsx
import { ScriptOnce } from '@tanstack/solid-router'
const themeScript = `(function() {
try {
const theme = localStorage.getItem('theme') || 'auto';
const resolved = theme === 'auto'
? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
: theme;
document.documentElement.classList.add(resolved);
} catch (e) {}
})();`
function ThemeProvider({ children }) {
return (
<>
{children}
>
)
}
```
--------------------------------
### Navigate with Prefix and Suffix Optional Parameters
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Use optional parameters with prefix or suffix syntax in the 'to' path. Set the parameter to undefined to omit it during navigation.
```tsx
// Navigate to file with optional name
Document File
// Navigate to file without optional name
Default File
```
--------------------------------
### Create root route with context
Source: https://tanstack.com/router/latest/docs/guide/data-loading.md
Initialize the root route with a typed context for dependency injection.
```tsx
import { createRootRouteWithContext } from '@tanstack/react-router'
// Create a root route using the createRootRouteWithContext<{...}>() function and pass it whatever types you would like to be available in your router context.
export const Route = createRootRouteWithContext<{
fetchPosts: typeof fetchPosts
}>()() // NOTE: the double call is on purpose, since createRootRouteWithContext is a factory ;)
```
--------------------------------
### createRoute Function Usage
Source: https://tanstack.com/router/latest/docs/api/router/createRouteFunction.md
Demonstrates how to use the createRoute function to define a root route with a path, loader, and component.
```APIDOC
## createRoute Function
The `createRoute` function returns a `Route` instance that can be used to build a route tree for the router.
### Method
`createRoute(options)`
### Parameters
#### Request Body
- **options** (`RouteOptions`) - Required - The options used to configure the route instance.
- **getParentRoute** (`() => Route`) - Required - A function that returns the parent route.
- **path** (`string`) - Required - The path for the route.
- **loader** (`() => Promise | TData`) - Optional - A function that loads data for the route.
- **component** (`React.ComponentType`) - Optional - The React component to render for the route.
### Response
#### Success Response (200)
- **Route** (`Route`) - A new `Route` instance.
### Request Example
```tsx
import { createRoute } from '@tanstack/react-router'
import { rootRoute } from './__root'
const Route = createRoute({
getParentRoute: () => rootRoute,
path: '/',
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return
{data}
}
```
```
--------------------------------
### Optimize Permission Checks with Memoization
Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md
Use useMemo to cache permission results and prevent unnecessary re-computations during renders.
```tsx
import { useMemo } from 'react'
function usePermissions() {
const { auth } = Route.useRouteContext()
const permissions = useMemo(
() => ({
canEditUsers: auth.hasPermission('users:write'),
canDeleteUsers: auth.hasPermission('users:delete'),
isAdmin: auth.hasRole('admin'),
isModerator: auth.hasAnyRole(['admin', 'moderator']),
}),
[auth.user?.roles, auth.user?.permissions],
)
return permissions
}
```
--------------------------------
### Create Routes Directory
Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md
Create the 'routes' directory within the 'src' directory to house your route files.
```sh
mkdir src/routes
```
--------------------------------
### Import Path Extensions
Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md
Configure how file extensions are handled in import paths within the generated route tree.
```APIDOC
### `addExtensions`
- Type: `boolean | string`
- Default: `false`
This option controls file extensions on import paths in the generated route tree.
- `false` — Extensions are stripped from import paths (e.g. `'./routes/posts'`)
- `true` — The original file extensions are kept (e.g. `'./routes/posts.tsx'`)
- `string` — The original extension is replaced with the provided one (e.g. `'js'` produces `'./routes/posts.js'`)
Passing a string is useful when your project uses ESM, since Node.js ESM requires `.js` extensions for imports even when the source files are `.ts` or `.tsx`.
```ts
// Example: replace .tsx/.ts extensions with .js in generated imports
TanStackRouterVite({
addExtensions: 'js',
})
```
```
--------------------------------
### Create Route Mask in SolidJS with TanStack Router
Source: https://tanstack.com/router/latest/docs/guide/route-masking.md
Demonstrates how to create a route mask using `createRouteMask` from `@tanstack/solid-router`. This involves defining the `routeTree`, the `from` route, and mapping parameters to the `to` route. The created mask is then passed to the router configuration.
```tsx
import { createRouteMask } from '@tanstack/solid-router'
const photoModalToPhotoMask = createRouteMask({
routeTree,
from: '/photos/$photoId/modal',
to: '/photos/$photoId',
params: (prev) => ({
photoId: prev.photoId,
}),
})
const router = createRouter({
routeTree,
routeMasks: [photoModalToPhotoMask],
})
```
--------------------------------
### Configure Babel for Solid
Source: https://tanstack.com/router/latest/docs/installation/with-webpack.md
Include the required presets in your .babelrc file when using Solid with Webpack.
```tsx
// .babelrc
{
"presets": ["babel-preset-solid", "@babel/preset-typescript"]
}
```
--------------------------------
### Configure package.json Scripts for CLI
Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md
Add scripts to your package.json to enable route generation and watching using the TanStack Router CLI.
```json
{
"scripts": {
"generate-routes": "tsr generate",
"watch-routes": "tsr watch",
"build": "npm run generate-routes && ...",
"dev": "npm run watch-routes && ..."
}
}
```
--------------------------------
### Initial Link Options without `linkOptions` (TypeScript)
Source: https://tanstack.com/router/latest/docs/guide/link-options.md
Illustrates a basic approach to defining link options as an object literal. This method has potential type-checking issues, as properties like `to` might be inferred too broadly, and type errors might only be caught when the options are spread into a `Link` component, rather than during the option definition itself.
```tsx
const dashboardLinkOptions = {
to: '/dashboard',
search: { search: '' },
}
function DashboardComponent() {
return
}
```
--------------------------------
### Route matching process for /blog
Source: https://tanstack.com/router/latest/docs/routing/route-matching.md
Visual representation of the matching process for the /blog URL.
```text
Root
❌ /
❌ about/us
❌ about
⏩ blog
✅ /
- new
- $postId
- *
```
--------------------------------
### Create Array of Reusable Link Options with `linkOptions` (TypeScript)
Source: https://tanstack.com/router/latest/docs/guide/link-options.md
Shows how to use `linkOptions` to type-check an array of navigation options, suitable for generating navigation bars or lists. Each object in the array is individually type-checked, ensuring that all navigation items are correctly defined. This is useful for scenarios where you need to loop over options to render multiple links.
```tsx
const options = linkOptions([
{
to: '/dashboard',
label: 'Summary',
activeOptions: { exact: true },
},
{
to: '/dashboard/invoices',
label: 'Invoices',
},
{
to: '/dashboard/users',
label: 'Users',
},
])
function DashboardComponent() {
return (
<>
>
)
}
```
--------------------------------
### Navigate Component
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
A component that triggers navigation immediately upon mounting, useful for client-side redirects.
```APIDOC
##
### Description
Navigates to a specified route immediately when the component mounts.
### Parameters
- **to** (string) - Required - The destination path.
- **params** (object) - Optional - Route parameters for the destination.
```
--------------------------------
### Subdomain to Path Routing with Rewrites
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Route subdomain requests to path-based routes and reverse the transformation for link generation. Handles `admin.example.com` and `api.example.com`.
```tsx
const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => {
const subdomain = url.hostname.split('.')[0]
// admin.example.com/users → /admin/users
if (subdomain === 'admin') {
url.pathname = '/admin' + url.pathname
}
// api.example.com/v1/users → /api/v1/users
else if (subdomain === 'api') {
url.pathname = '/api' + url.pathname
}
return url
},
output: ({ url }) => {
// Reverse the transformation for link generation
if (url.pathname.startsWith('/admin')) {
url.hostname = 'admin.example.com'
url.pathname = url.pathname.replace(/^\/admin/, '') || '/'
} else if (url.pathname.startsWith('/api')) {
url.hostname = 'api.example.com'
url.pathname = url.pathname.replace(/^\/api/, '') || '/'
}
return url
},
},
})
```
--------------------------------
### Legacy URL Migration with Rewrites
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Support old URLs by mapping them to new route structures. No output rewrite is needed as new URLs will be used going forward.
```tsx
const legacyPaths: Record = {
'/old-about': '/about',
'/old-contact': '/contact',
'/blog-posts': '/blog',
'/user-profile': '/account/profile',
}
const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => {
const newPath = legacyPaths[url.pathname]
if (newPath) {
url.pathname = newPath
}
return url
},
// No output rewrite needed - new URLs will be used going forward
},
})
```
--------------------------------
### Create Posts Index Route File
Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md
Defines the index route for '/posts/', typically used for the default view when navigating to the posts directory. Ensure this file is named `posts.index.tsx`.
```tsx
// src/routes/posts.index.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/posts/')({
component: PostsIndex,
})
```
--------------------------------
### Using defer with TanStack Router loaders and components
Source: https://tanstack.com/router/latest/docs/api/router/deferFunction.md
Demonstrates how to wrap a fetch promise using defer within a route loader and consume it using either the useAwaited hook or the Await component in a React component.
```tsx
import { defer } from '@tanstack/react-router'
const route = createRoute({
loader: () => {
const deferredPromise = defer(fetch('/api/data'))
return { deferredPromise }
},
component: MyComponent,
})
function MyComponent() {
const { deferredPromise } = Route.useLoaderData()
const data = useAwaited({ promise: deferredPromise })
// or
return (
{(data) =>
{JSON.stringify(data)}
}
)
}
```
--------------------------------
### Get Current Location with useLocation Hook (React)
Source: https://tanstack.com/router/latest/docs/api/router/useLocationHook.md
The useLocation hook from TanStack Router returns the current location object. It can optionally take a select function to return a specific property of the location, such as the pathname. This is useful for accessing routing information within React components.
```tsx
import { useLocation } from '@tanstack/react-router'
function Component() {
const location = useLocation()
// ^ ParsedLocation
// OR
const pathname = useLocation({
select: (location) => location.pathname,
})
// ^ string
// ...
}
```
--------------------------------
### Route matching process for /blog/my-post
Source: https://tanstack.com/router/latest/docs/routing/route-matching.md
Visual representation of the matching process for the /blog/my-post URL.
```text
Root
❌ /
❌ about/us
❌ about
⏩ blog
❌ /
❌ new
✅ $postId
- *
```
--------------------------------
### Create a Root Route with Context (Solid)
Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md
Define a root route with custom context for Solid applications, specifying the type of the context object.
```tsx
// Root route with Context
import { createRootRouteWithContext } from '@tanstack/solid-router'
import type { QueryClient } from '@tanstack/solid-query'
export interface MyRouterContext {
queryClient: QueryClient
}
const rootRoute = createRootRouteWithContext()
```
--------------------------------
### Deferred Loading with External Libraries (Solid)
Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md
This Solid.js snippet illustrates deferred data loading using an external library such as TanStack Query. The route loader triggers data fetching using library-specific functions (`prefetchQuery`, `ensureQueryData`). Components then retrieve this data using the library's hooks, enabling the router to render the route before all background data is fully resolved and cached.
```tsx
import { createFileRoute } from '@tanstack/solid-router'
import { slowDataOptions, fastDataOptions } from '~/api/query-options'
export const Route = createFileRoute('/posts/$postId')({
loader: async ({ context: { queryClient } }) => {
// Kick off the fetching of some slower data, but do not await it
queryClient.prefetchQuery(slowDataOptions())
// Fetch and await some data that resolves quickly
await queryClient.ensureQueryData(fastDataOptions())
},
})
```
--------------------------------
### Hydrate Application on Client
Source: https://tanstack.com/router/latest/docs/guide/ssr.md
Initializes the router and hydrates the application on the client side.
```tsx
import { hydrateRoot } from 'react-dom/client'
import { RouterClient } from '@tanstack/react-router/ssr/client'
import { createRouter } from './router'
const router = createRouter()
hydrateRoot(document, )
```
```tsx
import { hydrate } from 'solid-js/web'
import { RouterClient } from '@tanstack/solid-router/ssr/client'
import { createRouter } from './router'
const router = createRouter()
hydrate(() => , document.body)
```
--------------------------------
### Dynamic Post Route with Data Fetching (Solid)
Source: https://tanstack.com/router/latest/docs/guide/deferred-data-loading.md
This SolidJS code defines a dynamic route for individual posts using TanStack Router. It uses `useSuspenseQuery` from `@tanstack/solid-query` for asynchronous data fetching. The component manages loading states with Suspense and renders deferred data, with Solid-specific reactivity for data access.
```tsx
import { createFileRoute } from '@tanstack/solid-router'
import { useSuspenseQuery } from '@tanstack/solid-query'
import { slowDataOptions, fastDataOptions } from '~/api/query-options'
export const Route = createFileRoute('/posts/$postId')({
// ...
component: PostIdComponent,
})
function PostIdComponent() {
const fastData = useSuspenseQuery(fastDataOptions())
// do something with fastData
return (
Loading...}>
)
}
function SlowDataComponent() {
const data = useSuspenseQuery(slowDataOptions())
return
{data()}
}
```
--------------------------------
### Configure routeTreeFileHeader
Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md
Displays the default configuration for prepending content to the generated route tree file, typically used for disabling linters and type checkers.
```json
[
"/* eslint-disable */",
"// @ts-nocheck",
"// noinspection JSUnusedGlobalSymbols"
]
```
--------------------------------
### NotFoundRoute Class Configuration
Source: https://tanstack.com/router/latest/docs/api/router/NotFoundRouteClass.md
Documentation for the constructor and usage of the NotFoundRoute class.
```APIDOC
## NotFoundRoute Class
### Description
Creates a not-found/404 route instance to be used in router configuration. Note: This class is deprecated; use `notFoundComponent` instead.
### Constructor Options
- **options** (RouteOptions) - Required - An object containing route configuration excluding path, id, getParentRoute, caseSensitive, parseParams, and stringifyParams.
### Usage Example
```tsx
import { NotFoundRoute, createRouter } from '@tanstack/react-router'
import { Route as rootRoute } from './routes/__root'
import { routeTree } from './routeTree.gen'
const notFoundRoute = new NotFoundRoute({
getParentRoute: () => rootRoute,
component: () =>
Not found!!!
,
})
const router = createRouter({
routeTree,
notFoundRoute,
})
```
```
--------------------------------
### Solid Route Definition with Optional Locale Parameter
Source: https://tanstack.com/router/latest/docs/guide/path-params.md
Sets up a route with an optional locale parameter '/{-$locale}/' in Solid. This enables flexible URLs like '/', '/en', or '/fr'. It shows how to access route parameters and apply directionality based on the locale.
```tsx
// Route structure:
// routes/
// -{$locale}/
// index.tsx // /, /en, /fr
// about.tsx // /about, /en/about, /fr/about
// blog/
// index.tsx // /blog, /en/blog, /fr/blog
// $slug.tsx // /blog/post, /en/blog/post, /fr/blog/post
// routes/{-$locale}/index.tsx
export const Route = createFileRoute('/{-$locale}/')({
component: HomeComponent,
})
function HomeComponent() {
const params = Route.useParams()
const isRTL = ['ar', 'he', 'fa'].includes(params().locale || '')
return (
Welcome ({params().locale || 'en'})
{/* Localized content */}
)
}
// routes/{-$locale}/about.tsx
export const Route = createFileRoute('/{-$locale}/about')({
component: AboutComponent,
})
```
--------------------------------
### Configure URL Rewrites for Router Paths
Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md
Shows how to implement bidirectional URL transformation using the rewrite property to handle path prefixes like locales.
```typescript
import { createRouter } from '@tanstack/react-router';
const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => {
if (url.pathname.startsWith('/en')) {
url.pathname = url.pathname.replace(/^\/en/, '') || '/';
}
return url;
},
output: ({ url }) => {
url.pathname = `/en${url.pathname === '/' ? '' : url.pathname}`;
return url;
},
},
});
```
--------------------------------
### Customizing Layout Route Tokens with Regex
Source: https://tanstack.com/router/latest/docs/api/file-based-routing.md
Demonstrates how to configure the `routeToken` option to identify layout route files using regular expressions. This allows for more flexible naming conventions for layout files beyond a simple string match. The regex is matched against the entire final segment of the route path.
```json
{
"routeToken": { "regex": "[a-z]+-layout", "flags": "i" }
}
```
```ts
{
routeToken: /[a-z]+-layout/i
}
```
--------------------------------
### Route matching process for /
Source: https://tanstack.com/router/latest/docs/routing/route-matching.md
Visual representation of the matching process for the root URL.
```text
Root
✅ /
- about/us
- about
- blog
- /
- new
- $postId
- *
```
--------------------------------
### Define User Management Route with Permissions
Source: https://tanstack.com/router/latest/docs/how-to/setup-rbac.md
Uses createFileRoute to define a route with a beforeLoad hook for permission validation and a component that conditionally renders actions based on auth context.
```tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/_authenticated/_users/manage')({
beforeLoad: ({ context }) => {
// Additional permission check at the page level
if (!context.auth.hasPermission('users:write')) {
throw new Error('You need write permissions to manage users')
}
},
component: UserManagement,
})
function UserManagement() {
const { auth } = Route.useRouteContext()
const canEdit = auth.hasPermission('users:write')
const canDelete = auth.hasPermission('users:delete')
return (
User Management
Name
Email
Role
Actions
John Doe
john@example.com
User
{canEdit && (
)}
{canDelete && (
)}
Your Permissions:
{auth.user?.permissions.map((permission) => (
✓ {permission}
))}
)
}
```
--------------------------------
### createLink Integration
Source: https://tanstack.com/router/latest/docs/guide/custom-link.md
How to wrap third-party UI components with TanStack Router's createLink to enable navigation capabilities.
```APIDOC
## createLink Integration
### Description
Use the `createLink` utility to transform standard UI components into router-aware components that support preloading and navigation.
### Usage
- **MUI Link**: Wrap the component directly or via `React.forwardRef` for custom props.
- **MUI Button**: Set the `component` prop to `a` and wrap with `createLink`.
- **Mantine Anchor**: Use `createLink` to integrate Mantine's `Anchor` component.
### Implementation Example (MUI)
```tsx
import { createLink } from '@tanstack/react-router'
import { Link } from '@mui/material'
export const CustomLink = createLink(Link)
```
### Implementation Example (Mantine)
```tsx
import { createLink } from '@tanstack/react-router'
import { Anchor } from '@mantine/core'
const CreatedLinkComponent = createLink(Anchor)
```
```
--------------------------------
### Code-Splitting Routes with createLazyRoute
Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md
Demonstrates how to code-split route configurations using Route.lazy() and createLazyRoute. This involves separating route definitions into different files and dynamically importing them.
```tsx
export const Route = createLazyRoute('/posts')({
component: MyComponent,
})
function MyComponent() {
return
My Component
}
```
```tsx
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/posts',
}).lazy(() => import('./posts.lazy').then((d) => d.Route))
```
--------------------------------
### Create a Standard Root Route (React)
Source: https://tanstack.com/router/latest/docs/routing/code-based-routing.md
Initialize the root route for a React application using `createRootRoute` from `@tanstack/react-router`.
```tsx
// Standard root route
import { createRootRoute } from '@tanstack/react-router'
const rootRoute = createRootRoute()
```
--------------------------------
### Matching Routes Programmatically
Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md
Shows how to use .matchRoutes to resolve a pathname and search parameters against the route tree. It returns an array of route matches.
```typescript
const matches = router.matchRoutes('/users/123', { tab: 'profile' });
console.log(matches);
```
--------------------------------
### Navigate Component API
Source: https://tanstack.com/router/latest/docs/api/router/navigateComponent.md
Documentation for the Navigate component, which handles programmatic navigation to new locations.
```APIDOC
## Navigate Component
### Description
The `Navigate` component is used to navigate to a new location when rendered. It supports updates to pathname, search parameters, hash, and location state. Navigation is triggered within a `useEffect` hook.
### Props
- **...options** (NavigateOptions) - Required - The navigation options defining the target location (pathname, search, hash, state, etc.).
### Returns
- **null** - The component does not render any UI.
### Usage Example
```jsx
import { Navigate } from '@tanstack/react-router'
function MyComponent() {
return
}
```
```
--------------------------------
### Link Component with Preloading Delay Configuration
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Illustrates how to customize the delay before intent-based preloading is triggered by using the `preloadDelay` prop with a specified number of milliseconds.
```tsx
const link = (
Blog Post
)
```
--------------------------------
### Basic URL Rewrite Configuration
Source: https://tanstack.com/router/latest/docs/guide/url-rewrites.md
Configure input and output URL rewrites when creating your router. The input function transforms the browser URL to the router's internal URL, and the output function transforms the router's internal URL back to the browser's URL. Both functions receive a URL object and can mutate it, return a new URL, a href string, or undefined to skip the rewrite.
```tsx
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => {
// Transform browser URL → router internal URL
// Return the modified URL, a new URL, or undefined to skip
return url
},
output: ({ url }) => {
// Transform router internal URL → browser URL
// Return the modified URL, a new URL, or undefined to skip
return url
},
},
})
```
--------------------------------
### Importing from Excluded Files
Source: https://tanstack.com/router/latest/docs/routing/routing-concepts.md
Demonstrates importing components from files prefixed with a hyphen, which are ignored by the route generator.
```tsx
import { createFileRoute } from '@tanstack/react-router'
import { PostsTable } from './-posts-table'
import { PostsHeader } from './-components/header'
import { PostsFooter } from './-components/footer'
export const Route = createFileRoute('/posts')({
loader: () => fetchPosts(),
component: PostComponent,
})
function PostComponent() {
const posts = Route.useLoaderData()
return (
)
}
```
```tsx
import { createFileRoute } from '@tanstack/solid-router'
import { PostsTable } from './-posts-table'
import { PostsHeader } from './-components/header'
import { PostsFooter } from './-components/footer'
export const Route = createFileRoute('/posts')({
loader: () => fetchPosts(),
component: PostComponent,
})
function PostComponent() {
const posts = Route.useLoaderData()
return (
)
}
```
--------------------------------
### Route Type Properties and Methods
Source: https://tanstack.com/router/latest/docs/api/router/RouteType.md
An overview of the properties and methods available on a Route instance in TanStack Router.
```APIDOC
## Route Type
The `Route` type is used to describe a route instance.
### `.addChildren` method
- **Description**: Adds child routes to the route instance and returns the route instance (but with updated types to reflect the new children).
- **Type**: `(children: Route[]) => this`
### `.update` method
- **Description**: Updates the route instance with new options and returns the route instance (but with updated types to reflect the new options). It can be useful to update a route instance's options after it has been created to avoid circular type references.
- **Type**: `(options: Partial) => this`
### `.lazy` method
- **Description**: Updates the route instance with a new lazy importer which will be resolved lazily when loading the route. This can be useful for code splitting.
- **Type**: `(lazyImporter: () => Promise>) => this`
### `.redirect` method
- **Description**: A type-safe version of the `redirect` function that is pre-bound to the route's path. The `from` parameter is automatically set to the route's `fullPath`, enabling type-safe relative redirects.
- **Type**: `(opts?: RedirectOptions) => Redirect`
### Example Usage of `.redirect`
```tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard/settings')({
beforeLoad: ({ context }) => {
if (!context.user) {
// Type-safe redirect - 'from' is automatically '/dashboard/settings'
throw Route.redirect({
to: '../login', // Relative path to sibling route
})
}
},
})
```
### ...`RouteApi` methods
- All of the methods from [`RouteApi`](./RouteApiType.md) are available.
```
--------------------------------
### Initialize RouteApi instance
Source: https://tanstack.com/router/latest/docs/api/router/RouteApiClass.md
Demonstrates how to instantiate the RouteApi class with a specific route ID and use its pre-bound hooks within a React component. This approach is deprecated and should be replaced by getRouteApi.
```tsx
import { RouteApi } from '@tanstack/react-router'
const routeApi = new RouteApi({ id: '/posts' })
export function PostsPage() {
const posts = routeApi.useLoaderData()
// ...
}
```
--------------------------------
### Configure Protocol Allowlist for Router Security
Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md
Demonstrates how to define or extend the protocol allowlist to prevent XSS attacks by restricting allowed URL protocols in navigation.
```typescript
import { createRouter, DEFAULT_PROTOCOL_ALLOWLIST } from '@tanstack/react-router';
// Use a custom allowlist (replaces the default)
const router = createRouter({
routeTree,
protocolAllowlist: ['https:', 'mailto:'],
});
// Or extend the default allowlist
const router = createRouter({
routeTree,
protocolAllowlist: [...DEFAULT_PROTOCOL_ALLOWLIST, 'ftp:'],
});
```
--------------------------------
### Navigate API
Source: https://tanstack.com/router/latest/docs/api/router/RouterType.md
Navigates to a new location using the provided options.
```APIDOC
## navigate Method
### Description
Navigates to a new location.
### Method
`navigate`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **options** (NavigateOptions) - Required - The options for navigation.
### Request Example
```json
{
"to": "/dashboard",
"params": {
"userId": "123"
}
}
```
### Response
#### Success Response (200)
This method returns a Promise that resolves when navigation is complete.
#### Response Example
```json
null
```
```
--------------------------------
### Implement Base64 Search Serialization
Source: https://tanstack.com/router/latest/docs/guide/custom-search-param-serialization.md
Demonstrates how to customize search parameter serialization using Base64 encoding to improve URL compatibility. This requires custom binary encoding and decoding functions.
```tsx
import { Router, parseSearchWith, stringifySearchWith } from '@tanstack/react-router';
const router = createRouter({
parseSearch: parseSearchWith((value) => JSON.parse(decodeFromBinary(value))),
stringifySearch: stringifySearchWith((value) => encodeToBinary(JSON.stringify(value))),
});
function decodeFromBinary(str: string): string {
return decodeURIComponent(Array.prototype.map.call(atob(str), function (c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
function encodeToBinary(str: string): string {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
return String.fromCharCode(parseInt(p1, 16));
}));
}
```
--------------------------------
### Create Reusable Link Options with `linkOptions` (TypeScript)
Source: https://tanstack.com/router/latest/docs/guide/link-options.md
Demonstrates using the `linkOptions` function to create type-safe, reusable navigation options. This function eagerly type-checks the provided object literal, ensuring it conforms to expected link properties before it's used in components like `Link`, `navigate`, or `redirect`. It improves maintainability by catching type errors early.
```tsx
const dashboardLinkOptions = linkOptions({
to: '/dashboard',
search: { search: '' },
})
function DashboardComponent() {
const navigate = useNavigate()
return (
{/** can be used in navigate ** /}
)
}
export const Route = createFileRoute('/dashboard')({
component: DashboardComponent,
validateSearch: (input) => ({ search: input.search }),
beforeLoad: () => {
// can used in redirect
throw redirect(dashboardLinkOptions)
},
})
```
--------------------------------
### Create Typed Root Route (Solid)
Source: https://tanstack.com/router/latest/docs/guide/router-context.md
Use `createRootRouteWithContext` to define a typed root router context for your Solid application. This ensures type safety for injected dependencies.
```tsx
import {
createRootRouteWithContext,
createRouter,
} from '@tanstack/solid-router'
interface MyRouterContext {
user: User
}
// Use the routerContext to create your root route
const rootRoute = createRootRouteWithContext()({
component: App,
})
const routeTree = rootRoute.addChildren([
// ...
])
// Use the routerContext to create your router
const router = createRouter({
routeTree,
})
```
--------------------------------
### Accessing Route APIs with getRouteApi in Solid
Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md
Demonstrates using the getRouteApi helper function in SolidJS to access type-safe route APIs such as useLoaderData, useParams, etc., within a component file without needing to import the route directly.
```tsx
import { createRoute } from '@tanstack/solid-router'
import { MyComponent } from './MyComponent'
const route = createRoute({
path: '/my-route',
loader: () => ({
foo: 'bar',
}),
component: MyComponent,
})
```
```tsx
import { getRouteApi } from '@tanstack/solid-router'
const route = getRouteApi('/my-route')
export function MyComponent() {
const loaderData = route.useLoaderData()
// ^? { foo: string }
return
...
}
```
--------------------------------
### Imperative Navigation with Optional Parameters
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Use the useNavigate hook to perform navigation with optional parameters. Parameters can be cleared or updated using object or function patterns.
```tsx
function Component() {
const navigate = useNavigate()
const clearFilters = () => {
navigate({
to: '/posts/{-$category}/{-$tag}',
params: { category: undefined, tag: undefined },
})
}
const setCategory = (category: string) => {
navigate({
to: '/posts/{-$category}/{-$tag}',
params: (prev) => ({ ...prev, category }),
})
}
const applyFilters = (category?: string, tag?: string) => {
navigate({
to: '/posts/{-$category}/{-$tag}',
params: { category, tag },
})
}
}
```
--------------------------------
### Create Hash History for React and Solid Routers
Source: https://tanstack.com/router/latest/docs/guide/history-types.md
Illustrates the creation of a hash history instance for TanStack Router. This method is beneficial in environments where server rewrites to index.html are not feasible, using the URL hash for history management.
```typescript
import { createHashHistory, createRouter } from '@tanstack/react-router'
const hashHistory = createHashHistory()
const router = createRouter({ routeTree, history: hashHistory })
```
```typescript
import { createHashHistory, createRouter } from '@tanstack/solid-router'
const hashHistory = createHashHistory()
const router = createRouter({ routeTree, history: hashHistory })
```
--------------------------------
### Define a route loader with TanStack Query
Source: https://tanstack.com/router/latest/docs/integrations/query.md
Uses queryOptions to define a query and triggers it within the route loader to enable streaming to the client.
```tsx
import { createFileRoute } from '@tanstack/react-router'
import { queryOptions, useQuery } from '@tanstack/react-query'
const userQuery = (id: string) =>
queryOptions({
queryKey: ['user', id],
queryFn: () => fetch(`/api/users/${id}`).then((r) => r.json()),
})
export const Route = createFileRoute('/user/$id')({
loader: ({ params }) => {
// do not await this nor return the promise, just kick off the query to stream it to the client
context.queryClient.fetchQuery(userQuery(params.id))
},
})
```
--------------------------------
### Update Main Entry File with Router
Source: https://tanstack.com/router/latest/docs/installation/migrate-from-react-location.md
Configures and renders the TanStack Router in the main application entry point (`src/index.tsx`). This involves creating a router instance with the generated route tree and wrapping the application with `RouterProvider`.
```tsx
// src/index.tsx
import React from 'react'
import ReactDOM from 'react-dom'
import { createRouter, RouterProvider } from '@tanstack/react-router'
// Import the generated route tree
import { routeTree } from './routeTree.gen'
// Create a new router instance
const router = createRouter({ routeTree })
// Register the router instance for type safety
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
const domElementId = 'root' // Assuming you have a root element with the id 'root'
// Render the app
const rootElement = document.getElementById(domElementId)
if (!rootElement) {
throw new Error(`Element with id ${domElementId} not found`)
}
ReactDOM.createRoot(rootElement).render(
,
)
```
--------------------------------
### Wrap Router with Context Provider
Source: https://tanstack.com/router/latest/docs/api/router/RouterOptionsType.md
Demonstrates how to use the Wrap property to provide a React context to the entire router instance. This should only be used for non-DOM rendering components like providers.
```tsx
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
// ...
Wrap: ({ children }) => {
return {children}
},
})
```
--------------------------------
### Resetting Mutation State with Mutation Keys
Source: https://tanstack.com/router/latest/docs/guide/data-mutations.md
Demonstrates how to bind a mutation's state to a route parameter using a key. When the roomId changes, the mutation state is automatically cleared.
```tsx
const routeApi = getRouteApi('/room/$roomId/chat')
function ChatRoom() {
const { roomId } = routeApi.useParams()
const sendMessageMutation = useCoolMutation({
fn: sendMessage,
key: ['sendMessage', roomId],
})
const test = () => {
sendMessageMutation.mutate({ roomId, message: 'Hello!' })
sendMessageMutation.mutate({ roomId, message: 'How are you?' })
sendMessageMutation.mutate({ roomId, message: 'Goodbye!' })
}
return (
<>
{sendMessageMutation.submissions.map((submission) => {
return (
{submission.status}
{submission.message}
)
})}
>
)
}
```
--------------------------------
### Default Configuration for React Projects
Source: https://tanstack.com/router/latest/docs/installation/with-router-cli.md
Default configuration options for TanStack Router CLI when targeting React projects.
```json
{
"routesDirectory": "./src/routes",
"generatedRouteTree": "./src/routeTree.gen.ts",
"routeFileIgnorePrefix": "-",
"quoteStyle": "single",
"target": "react"
}
```
--------------------------------
### Navigate with Fully Optional Parameters
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Define routes where all path segments are optional. Set parameters to undefined to remove them from the URL.
```tsx
// Navigate to specific date
Christmas 2023
// Navigate to partial date
December 2023
// Navigate to root with all parameters removed
Home
```
--------------------------------
### Accessing the Root Route's Match
Source: https://tanstack.com/router/latest/docs/api/router/useMatchHook.md
Demonstrates how to use `useMatch` with the `rootRouteId` token to access the root route's match information.
```APIDOC
## Example: Accessing the root route's match
### Description
This example shows how to use `useMatch` with the `rootRouteId` token to specifically access the match object for the root route.
### Code
```tsx
import {
useMatch,
rootRouteId, // Use this token
} from '@tanstack/react-router'
function Component() {
const match = useMatch({ from: rootRouteId })
// match is a strict RouteMatch object for the root route
// ...
}
```
```
--------------------------------
### Implement Code Splitting with .lazy.tsx
Source: https://tanstack.com/router/latest/docs/guide/code-splitting.md
Demonstrates splitting a route file into a critical configuration file and a lazy-loaded component file. This approach separates the loader logic from the UI component to improve initial load performance.
```tsx
import { createFileRoute } from '@tanstack/react-router';
import { fetchPosts } from './api';
export const Route = createFileRoute('/posts')({
loader: fetchPosts,
});
```
```tsx
import { createLazyFileRoute } from '@tanstack/react-router';
export const Route = createLazyFileRoute('/posts')({
component: Posts,
});
function Posts() {
// ...
}
```
--------------------------------
### Importing TanStack Router Devtools
Source: https://tanstack.com/router/latest/docs/devtools.md
Import the standard devtools component for development environments. Use the 'InProd' variant if you need to force the devtools to appear in production builds.
```tsx
import { TanStackRouterDevtools } from '@tanstack/react-router-devtools';
import { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools';
```
```tsx
import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools';
import { TanStackRouterDevtoolsInProd } from '@tanstack/solid-router-devtools';
```
--------------------------------
### Implement Code-Splitting in Routes
Source: https://tanstack.com/router/latest/docs/decisions-on-dx.md
Illustrates how to use lazyRouteComponent to dynamically import route components, reducing initial bundle size in manual route configurations.
```typescript
import { createRoute, lazyRouteComponent } from '@tanstack/react-router'
import { postsRoute } from './postsRoute'
export const postsIndexRoute = createRoute({
getParentRoute: () => postsRoute,
path: '/',
component: lazyRouteComponent(() => import('../page-components/posts/index')),
})
```
--------------------------------
### Route Head Configuration
Source: https://tanstack.com/router/latest/docs/guide/document-head-management.md
Configure head tags for a route using the `head` property in `createRootRoute`.
```APIDOC
## Route Head Configuration
### Description
Configure head tags for a route using the `head` property in `createRootRoute`.
### Method
N/A (Configuration)
### Endpoint
N/A (Configuration)
### Parameters
#### Request Body
- **head** (function) - Required - A function that returns an object with `title`, `meta`, `links`, `styles`, and `scripts` properties.
- **meta** (array) - Optional - An array of meta tag objects.
- **name** (string) - Optional - The name attribute for the meta tag.
- **content** (string) - Optional - The content attribute for the meta tag.
- **title** (string) - Optional - The title for the document.
- **links** (array) - Optional - An array of link tag objects.
- **rel** (string) - Required - The rel attribute for the link tag.
- **href** (string) - Required - The href attribute for the link tag.
- **styles** (array) - Optional - An array of style tag objects.
- **media** (string) - Optional - The media attribute for the style tag.
- **children** (string) - Required - The content of the style tag.
- **scripts** (array) - Optional - An array of script tag objects.
- **src** (string) - Optional - The src attribute for the script tag.
### Request Example
```tsx
export const Route = createRootRoute({
head: () => ({
meta: [
{
name: 'description',
content: 'My App is a web application',
},
{
title: 'My App',
},
],
links: [
{
rel: 'icon',
href: '/favicon.ico',
},
],
styles: [
{
media: 'all and (max-width: 500px)',
children: `p {
color: blue;
background-color: yellow;
}`,
},
],
scripts: [
{
src: 'https://www.google-analytics.com/analytics.js',
},
],
}),
})
```
### Response
N/A (Configuration)
```
--------------------------------
### Create static links
Source: https://tanstack.com/router/latest/docs/guide/navigation.md
Basic usage of the Link component for static navigation in React and Solid.
```tsx
import { Link } from '@tanstack/react-router'
const link = About
```
```tsx
import { Link } from '@tanstack/solid-router'
const link = About
```
--------------------------------
### Implement AuthProvider with Persistence
Source: https://tanstack.com/router/latest/docs/how-to/setup-authentication.md
Use `useState` and `useEffect` within `AuthProvider` to manage authentication state and restore it from `localStorage` on app load. Includes loading state management.
```tsx
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState(null)
const [isAuthenticated, setIsAuthenticated] = useState(false)
const [isLoading, setIsLoading] = useState(true)
// Restore auth state on app load
useEffect(() => {
const token = localStorage.getItem('auth-token')
if (token) {
// Validate token with your API
fetch('/api/validate-token', {
headers: { Authorization: `Bearer ${token}` },
})
.then((response) => response.json())
.then((userData) => {
if (userData.valid) {
setUser(userData.user)
setIsAuthenticated(true)
} else {
localStorage.removeItem('auth-token')
}
})
.catch(() => {
localStorage.removeItem('auth-token')
})
.finally(() => {
setIsLoading(false)
})
} else {
setIsLoading(false)
}
}, [])
// Show loading state while checking auth
if (isLoading) {
return (
Loading...
)
}
// ... rest of the provider logic
}
```
--------------------------------
### scripts Method
Source: https://tanstack.com/router/latest/docs/api/router/RouteOptionsType.md
Shorthand helper for injecting script elements.
```APIDOC
## scripts
### Description
A shorthand helper to return only