declare const _default: "# Authenticated Routes\n\nAuthentication is an extremely common requirement for web applications. In this guide, we'll walk through how to use TanStack Router to build protected routes, and how to redirect users to login if they try to access them.\n\n## The `route.beforeLoad` Option\n\nThe `route.beforeLoad` option allows you to specify a function that will be called before a route is loaded. It receives all of the same arguments that the `route.loader` function does. This is a great place to check if a user is authenticated, and redirect them to a login page if they are not.\n\nThe `beforeLoad` function runs in relative order to these other route loading functions:\n\n- Route Matching (Top-Down)\n - `route.params.parse`\n - `route.validateSearch`\n- Route Loading (including Preloading)\n - **`route.beforeLoad`**\n - `route.onError`\n- Route Loading (Parallel)\n - `route.component.preload?`\n - `route.load`\n\n**It's important to know that the `beforeLoad` function for a route is called _before any of its child routes' `beforeLoad` functions_.** It is essentially a middleware function for the route and all of its children.\n\n**If you throw an error in `beforeLoad`, none of its children will attempt to load**.\n\n## Redirecting\n\nWhile not required, some authentication flows require redirecting to a login page. To do this, you can **throw a `redirect()`** from `beforeLoad`:\n\n```tsx\n// src/routes/_authenticated.tsx\nexport const Route = createFileRoute('/_authenticated')({\n beforeLoad: async ({ location }) => {\n if (!isAuthenticated()) {\n throw redirect({\n to: '/login',\n search: {\n // Use the current location to power a redirect after login\n // (Do not use `router.state.resolvedLocation` as it can\n // potentially lag behind the actual current location)\n redirect: location.href,\n },\n })\n }\n },\n})\n```\n\n> [!TIP]\n> The `redirect()` function takes all of the same options as the `navigate` function, so you can pass options like `replace: true` if you want to replace the current history entry instead of adding a new one.\n\n### Handling Auth Check Failures\n\nIf your authentication check can throw errors (network failures, token validation, etc.), wrap it in try/catch:\n\n\n\n# React\n\n```tsx\nimport { createFileRoute, redirect, isRedirect } from '@tanstack/react-router'\n\n// src/routes/_authenticated.tsx\nexport const Route = createFileRoute('/_authenticated')({\n beforeLoad: async ({ location }) => {\n try {\n const user = await verifySession() // might throw on network error\n if (!user) {\n throw redirect({\n to: '/login',\n search: { redirect: location.href },\n })\n }\n return { user }\n } catch (error) {\n // Re-throw redirects (they're intentional, not errors)\n if (isRedirect(error)) throw error\n\n // Auth check failed (network error, etc.) - redirect to login\n throw redirect({\n to: '/login',\n search: { redirect: location.href },\n })\n }\n },\n})\n```\n\n# Solid\n\n```tsx\nimport { createFileRoute, redirect, isRedirect } from '@tanstack/solid-router'\n\n// src/routes/_authenticated.tsx\nexport const Route = createFileRoute('/_authenticated')({\n beforeLoad: async ({ location }) => {\n try {\n const user = await verifySession() // might throw on network error\n if (!user) {\n throw redirect({\n to: '/login',\n search: { redirect: location.href },\n })\n }\n return { user }\n } catch (error) {\n // Re-throw redirects (they're intentional, not errors)\n if (isRedirect(error)) throw error\n\n // Auth check failed (network error, etc.) - redirect to login\n throw redirect({\n to: '/login',\n search: { redirect: location.href },\n })\n }\n },\n})\n```\n\n\n\nThe [`isRedirect()`](../api/router/isRedirectFunction.md) helper distinguishes between actual errors and intentional redirects.\n\nOnce you have authenticated a user, it's also common practice to redirect them back to the page they were trying to access. To do this, you can utilize the `redirect` search param that we added in our original redirect. Since we'll be replacing the entire URL with what it was, `router.history.push` is better suited for this than `router.navigate`:\n\n```tsx\nrouter.history.push(search.redirect)\n```\n\n## Non-Redirected Authentication\n\nSome applications choose to not redirect users to a login page, and instead keep the user on the same page and show a login form that either replaces the main content or hides it via a modal. This is also possible with TanStack Router by simply short circuiting rendering the `` that would normally render the child routes:\n\n```tsx\n// src/routes/_authenticated.tsx\nexport const Route = createFileRoute('/_authenticated')({\n component: () => {\n if (!isAuthenticated()) {\n return \n }\n\n return \n },\n})\n```\n\nThis keeps the user on the same page, but still allows you to render a login form. Once the user is authenticated, you can simply render the `` and the child routes will be rendered.\n\n## Authentication using React context/hooks\n\nIf your authentication flow relies on interactions with React context and/or hooks, you'll need to pass down your authentication state to TanStack Router using `router.context` option.\n\n> [!IMPORTANT]\n> React hooks are not meant to be consumed outside of React components. If you need to use a hook outside of a React component, you need to extract the returned state from the hook in a component that wraps your `` and then pass the returned value down to TanStack Router.\n\nWe'll cover the `router.context` options in-detail in the [Router Context](./router-context.md) section.\n\nHere's an example that uses React context and hooks for protecting authenticated routes in TanStack Router. See the entire working setup in the [Authenticated Routes example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes).\n\n\n\n# React\n\n\n\n```tsx title=\"src/routes/__root.tsx\"\nimport { createRootRouteWithContext } from '@tanstack/react-router'\n\ninterface MyRouterContext {\n // The ReturnType of your useAuth hook or the value of your AuthContext\n auth: AuthState\n}\n\nexport const Route = createRootRouteWithContext()({\n component: () => ,\n})\n```\n\n```tsx title=\"src/router.tsx\"\nimport { createRouter } from '@tanstack/react-router'\n\nimport { routeTree } from './routeTree.gen'\n\nexport const router = createRouter({\n routeTree,\n context: {\n // auth will initially be undefined\n // We'll be passing down the auth state from within a React component\n auth: undefined!,\n },\n})\n```\n\n```tsx title=\"src/App.tsx\"\nimport { RouterProvider } from '@tanstack/react-router'\n\nimport { AuthProvider, useAuth } from './auth'\n\nimport { router } from './router'\n\nfunction InnerApp() {\n const auth = useAuth()\n return \n}\n\nfunction App() {\n return (\n \n \n \n )\n}\n```\n\n\n\n# Solid\n\n\n\n```tsx title=\"src/routes/__root.tsx\"\nimport { createRootRouteWithContext } from '@tanstack/solid-router'\n\ninterface MyRouterContext {\n // The ReturnType of your useAuth hook or the value of your AuthContext\n auth: AuthState\n}\n\nexport const Route = createRootRouteWithContext()({\n component: () => ,\n})\n```\n\n```tsx title=\"src/router.tsx\"\nimport { createRouter } from '@tanstack/solid-router'\n\nimport { routeTree } from './routeTree.gen'\n\nexport const router = createRouter({\n routeTree,\n context: {\n // auth will initially be undefined\n // We'll be passing down the auth state from within a React component\n auth: undefined!,\n },\n})\n```\n\n```tsx title=\"src/App.tsx\"\nimport { RouterProvider } from '@tanstack/solid-router'\n\nimport { AuthProvider, useAuth } from './auth'\n\nimport { router } from './router'\n\nfunction InnerApp() {\n const auth = useAuth()\n return \n}\n\nfunction App() {\n return (\n \n \n \n )\n}\n```\n\n\n\n\n\nThen in the authenticated route, you can check the auth state using the `beforeLoad` function, and **throw a `redirect()`** to your **Login route** if the user is not signed-in.\n\n\n\n# React\n\n```tsx title=\"src/routes/dashboard.route.tsx\"\nimport { createFileRoute, redirect } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/dashboard')({\n beforeLoad: ({ context, location }) => {\n if (!context.auth.isAuthenticated) {\n throw redirect({\n to: '/login',\n search: {\n redirect: location.href,\n },\n })\n }\n },\n})\n```\n\n# Solid\n\n```tsx title=\"src/routes/dashboard.route.tsx\"\nimport { createFileRoute, redirect } from '@tanstack/solid-router'\n\nexport const Route = createFileRoute('/dashboard')({\n beforeLoad: ({ context, location }) => {\n if (!context.auth.isAuthenticated()) {\n throw redirect({\n to: '/login',\n search: {\n redirect: location.href,\n },\n })\n }\n },\n})\n```\n\n\n\nYou can _optionally_, also use the [Non-Redirected Authentication](#non-redirected-authentication) approach to show a login form instead of calling a **redirect**.\n\nThis approach can also be used in conjunction with Pathless or Layout Route to protect all routes under their parent route.\n\n## Related How-To Guides\n\nFor detailed, step-by-step implementation guides, see:\n\n- [How to Set Up Basic Authentication](../how-to/setup-authentication.md) - Complete setup with React Context and protected routes\n- [How to Integrate Authentication Providers](../how-to/setup-auth-providers.md) - Use Auth0, Clerk, or Supabase\n- [How to Set Up Role-Based Access Control](../how-to/setup-rbac.md) - Implement permissions and role-based routing\n\n## Examples\n\nWorking authentication examples are available in the repository:\n\n- [Basic Authentication Example](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes) - Simple authentication with context\n- [Firebase Authentication](https://github.com/TanStack/router/tree/main/examples/react/authenticated-routes-firebase) - Firebase Auth integration\n- [TanStack Start Auth Examples](https://github.com/TanStack/router/tree/main/examples/react) - Various auth implementations with TanStack Start\n\n# Automatic Code Splitting\n\nThe automatic code splitting feature in TanStack Router allows you to optimize your application's bundle size by lazily loading route components and their associated data. This is particularly useful for large applications where you want to minimize the initial load time by only loading the necessary code for the current route.\n\nTo turn this feature on, simply set the `autoCodeSplitting` option to `true` in your bundler plugin configuration. This enables the router to automatically handle code splitting for your routes without requiring any additional setup.\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n plugins: [\n tanstackRouter({\n autoCodeSplitting: true, // Enable automatic code splitting\n }),\n ],\n})\n```\n\nBut that's just the beginning! TanStack Router's automatic code splitting is not only easy to enable, but it also provides powerful customization options to tailor how your routes are split into chunks. This allows you to optimize your application's performance based on your specific needs and usage patterns.\n\n## How does it work?\n\nTanStack Router's automatic code splitting works by transforming your route files both during 'development' and at 'build' time. It rewrites the route definitions to use lazy-loading wrappers for components and loaders, which allows the bundler to group these properties into separate chunks.\n\n> [!TIP]\n> A **chunk** is a file that contains a portion of your application's code, which can be loaded on demand. This helps reduce the initial load time of your application by only loading the code that is needed for the current route.\n\nSo when your application loads, it doesn't include all the code for every route. Instead, it only includes the code for the routes that are initially needed. As users navigate through your application, additional chunks are loaded on demand.\n\nThis happens seamlessly, without requiring you to manually split your code or manage lazy loading. The TanStack Router bundler plugin takes care of everything, ensuring that your routes are optimized for performance right out of the box.\n\n### The transformation process\n\nWhen you enable automatic code splitting, the bundler plugin does this by using static code analysis look at your the code in your route files to transform them into optimized outputs.\n\nThis transformation process produces two key outputs when each of your route files are processed:\n\n1. **Reference File**: The bundler plugin takes your original route file (e.g., `posts.route.tsx`) and modifies the values for properties like `component` or `pendingComponent` to use special lazy-loading wrappers that'll fetch the actual code later. These wrappers point to a \"virtual\" file that the bundler will resolve later on.\n2. **Virtual File**: When the bundler sees a request for one of these virtual files (e.g., `posts.route.tsx?tsr-split=component`), it intercepts it to generate a new, minimal on-the-fly file that _only_ contains the code for the requested properties (e.g., just the `PostsComponent`).\n\nThis process ensures that your original code remains clean and readable, while the actual bundled output is optimized for initial bundle size.\n\n### What gets code split?\n\nThe decision of what to split into separate chunks is crucial for optimizing your application's performance. TanStack Router uses a concept called \"**Split Groupings**\" to determine how different parts of your route should be bundled together.\n\nSplit groupings are arrays of properties that tell TanStack Router how to bundle different parts of your route together. Each grouping is an list of property names that you want to bundle together into a single lazy-loaded chunk.\n\nThe available properties to split are:\n\n- `component`\n- `errorComponent`\n- `pendingComponent`\n- `notFoundComponent`\n- `loader`\n\nBy default, TanStack Router uses the following split groupings:\n\n```sh\n[\n ['component'],\n ['errorComponent'],\n ['notFoundComponent']\n]\n```\n\nThis means that it creates three separate lazy-loaded chunks for each route. Resulting in:\n\n- One for the main component\n- One for the error component\n- And one for the not-found component.\n\n### Rules of Splitting\n\nFor automatic code splitting to work, there are some rules in-place to make sure that this process can reliably and predictably happen.\n\n#### Do not export route properties\n\nRoute properties like `component`, `loader`, etc., should not be exported from the route file. Exporting these properties results in them being bundled into the main application bundle, which means that they will not be code-split.\n\n```tsx\nexport const Route = createRoute('/posts')({\n // ...\n notFoundComponent: PostsNotFoundComponent,\n})\n\n// \u274C Do NOT do this!\n// Exporting the notFoundComponent will prevent it from being code-split\n// and will be included in the main bundle.\nexport function PostsNotFoundComponent() {\n // \u274C\n // ...\n}\n\nfunction PostsNotFoundComponent() {\n // \u2705\n // ...\n}\n```\n\n**That's it!** There are no other restrictions. You can use any other JavaScript or TypeScript features in your route files as you normally would. If you run into any issues, please [open an issue](https://github.com/tanstack/router/issues) on GitHub.\n\n## Granular control\n\nFor most applications, the default behavior of using `autoCodeSplitting: true` is sufficient. However, TanStack Router provides several options to customize how your routes are split into chunks, allowing you to optimize for specific use cases or performance needs.\n\n### Global code splitting behavior (`defaultBehavior`)\n\nYou can change how TanStack Router splits your routes by changing the `defaultBehavior` option in your bundler plugin configuration. This allows you to define how different properties of your routes should be bundled together.\n\nFor example, to bundle all UI-related components into a single chunk, you could configure it like this:\n\n```ts title=\"vite.config.ts\"\nimport { defineConfig } from 'vite'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n plugins: [\n tanstackRouter({\n autoCodeSplitting: true,\n codeSplittingOptions: {\n defaultBehavior: [\n [\n 'component',\n 'pendingComponent',\n 'errorComponent',\n 'notFoundComponent',\n ], // Bundle all UI components together\n ],\n },\n }),\n ],\n})\n```\n\n### Advanced programmatic control (`splitBehavior`)\n\nFor complex rulesets, you can use the `splitBehavior` function in your vite config to programmatically define how routes should be split into chunks based on their `routeId`. This function allows you to implement custom logic for grouping properties together, giving you fine-grained control over the code splitting behavior.\n\n```ts title=\"vite.config.ts\"\nimport { defineConfig } from 'vite'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n plugins: [\n tanstackRouter({\n autoCodeSplitting: true,\n codeSplittingOptions: {\n splitBehavior: ({ routeId }) => {\n // For all routes under /posts, bundle the loader and component together\n if (routeId.startsWith('/posts')) {\n return [['loader', 'component']]\n }\n // All other routes will use the `defaultBehavior`\n },\n },\n }),\n ],\n})\n```\n\n### Per-route overrides (`codeSplitGroupings`)\n\nFor ultimate control, you can override the global configuration directly inside a route file by adding a `codeSplitGroupings` property. This is useful for routes that have unique optimization needs.\n\n```tsx title=\"src/routes/posts.route.tsx\"\nimport { loadPostsData } from './-heavy-posts-utils'\n\nexport const Route = createFileRoute('/posts')({\n // For this specific route, bundle the loader and component together.\n codeSplitGroupings: [['loader', 'component']],\n loader: () => loadPostsData(),\n component: PostsComponent,\n})\n\nfunction PostsComponent() {\n // ...\n}\n```\n\nThis will create a single chunk that includes both the `loader` and the `component` for this specific route, overriding both the default behavior and any programmatic split behavior defined in your bundler config.\n\n### Configuration order matters\n\nThis guide has so far describe three different ways to configure how TanStack Router splits your routes into chunks.\n\nTo make sure that the different configurations do not conflict with each other, TanStack Router uses the following order of precedence:\n\n1. **Per-route overrides**: The `codeSplitGroupings` property inside a route file takes the highest precedence. This allows you to define specific split groupings for individual routes.\n2. **Programmatic split behavior**: The `splitBehavior` function in your bundler config allows you to define custom logic for how routes should be split based on their `routeId`.\n3. **Default behavior**: The `defaultBehavior` option in your bundler config serves as the fallback for any routes that do not have specific overrides or custom logic defined. This is the base configuration that applies to all routes unless overridden.\n\n### Splitting the Data Loader\n\nThe `loader` function is responsible for fetching data needed by the route. By default, it is bundled with into your \"reference file\" and loaded in the initial bundle. However, you can also split the `loader` into its own chunk if you want to optimize further.\n\n> [!CAUTION]\n> Moving the `loader` into its own chunk is a **performance trade-off**. It introduces an additional trip to the server before the data can be fetched, which can lead to slower initial page loads. This is because the `loader` **must** be fetched and executed before the route can render its component.\n> Therefore, we recommend keeping the `loader` in the initial bundle unless you have a specific reason to split it.\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n plugins: [\n tanstackRouter({\n autoCodeSplitting: true,\n codeSplittingOptions: {\n defaultBehavior: [\n ['loader'], // The loader will be in its own chunk\n ['component'],\n // ... other component groupings\n ],\n },\n }),\n ],\n})\n```\n\nWe highly discourage splitting the `loader` unless you have a specific use case that requires it. In most cases, not splitting off the `loader` and keep it in the main bundle is the best choice for performance.\n\n# Code Splitting\n\nCode splitting and lazy loading is a powerful technique for improving the bundle size and load performance of an application.\n\n- Reduces the amount of code that needs to be loaded on initial page load\n- Code is loaded on-demand when it is needed\n- Results in more chunks that are smaller in size that can be cached more easily by the browser.\n\n## How does TanStack Router split code?\n\nTanStack Router separates code into two categories:\n\n- **Critical Route Configuration** - The code that is required to render the current route and kick off the data loading process as early as possible.\n - Path Parsing/Serialization\n - Search Param Validation\n - Loaders, Before Load\n - Route Context\n - Static Data\n - Links\n - Scripts\n - Styles\n - All other route configuration not listed below\n\n- **Non-Critical/Lazy Route Configuration** - The code that is not required to match the route, and can be loaded on-demand.\n - Route Component\n - Error Component\n - Pending Component\n - Not-found Component\n\n> \uD83E\uDDE0 **Why is the loader not split?**\n>\n> - The loader is already an asynchronous boundary, so you pay double to both get the chunk _and_ wait for the loader to execute.\n> - Categorically, it is less likely to contribute to a large bundle size than a component.\n> - The loader is one of the most important preloadable assets for a route, especially if you're using a default preload intent, like hovering over a link, so it's important for the loader to be available without any additional async overhead.\n>\n> Knowing the disadvantages of splitting the loader, if you still want to go ahead with it, head over to the [Data Loader Splitting](#data-loader-splitting) section.\n\n## Encapsulating a route's files into a directory\n\nSince TanStack Router's file-based routing system is designed to support both flat and nested file structures, it's possible to encapsulate a route's files into a single directory without any additional configuration.\n\nTo encapsulate a route's files into a directory, move the route file itself into a `.route` file within a directory with the same name as the route file.\n\nFor example, if you have a route file named `posts.tsx`, you would create a new directory named `posts` and move the `posts.tsx` file into that directory, renaming it to `route.tsx`.\n\n**Before**\n\n- `posts.tsx`\n\n**After**\n\n- `posts`\n - `route.tsx`\n\n## Approaches to code splitting\n\nTanStack Router supports multiple approaches to code splitting. If you are using code-based routing, skip to the [Code-Based Splitting](#code-based-splitting) section.\n\nWhen you are using file-based routing, you can use the following approaches to code splitting:\n\n- [Using automatic code-splitting \u2728](#using-automatic-code-splitting)\n- [Using the `.lazy.tsx` suffix](#using-the-lazytsx-suffix)\n- [Using Virtual Routes](#using-virtual-routes)\n\n## Using automatic code-splitting\u2728\n\nThis is the easiest and most powerful way to code split your route files.\n\nWhen using the `autoCodeSplitting` feature, TanStack Router will automatically code split your route files based on the non-critical route configuration mentioned above.\n\n> [!IMPORTANT]\n> The automatic code-splitting feature is **ONLY** available when you are using file-based routing with one of our [supported bundlers](../routing/file-based-routing.md#getting-started-with-file-based-routing).\n> This will **NOT** work if you are **only** using the CLI (`@tanstack/router-cli`).\n\nTo enable automatic code-splitting, you just need to add the following to the configuration of your TanStack Router Bundler Plugin:\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n plugins: [\n tanstackRouter({\n // ...\n autoCodeSplitting: true,\n }),\n react(), // Make sure to add this plugin after the TanStack Router Bundler plugin\n ],\n})\n```\n\nThat's it! TanStack Router will automatically code-split all your route files by their critical and non-critical route configurations.\n\nIf you want more control over the code-splitting process, head over to the [Automatic Code Splitting](./automatic-code-splitting.md) guide to learn more about the options available.\n\n## Using the `.lazy.tsx` suffix\n\nIf you are not able to use the automatic code-splitting feature, you can still code-split your route files using the `.lazy.tsx` suffix. It is **as easy as moving your code into a separate file with a `.lazy.tsx` suffix** and using the `createLazyFileRoute` function instead of `createFileRoute`.\n\n> [!IMPORTANT]\n> The `__root.tsx` route file, using either `createRootRoute` or `createRootRouteWithContext`, does not support code splitting, since it's always rendered regardless of the current route.\n\nThese are the only options that `createLazyFileRoute` supports:\n\n| Export Name | Description |\n| ------------------- | --------------------------------------------------------------------- |\n| `component` | The component to render for the route. |\n| `errorComponent` | The component to render when an error occurs while loading the route. |\n| `pendingComponent` | The component to render while the route is loading. |\n| `notFoundComponent` | The component to render if a not-found error gets thrown. |\n\n### Example code splitting with `.lazy.tsx`\n\nWhen you are using `.lazy.tsx` you can split your route into two files to enable code splitting:\n\n**Before (Single File)**\n\n\n\n# React\n\n```tsx title=\"src/routes/posts.tsx\"\nimport { createFileRoute } from '@tanstack/react-router'\nimport { fetchPosts } from './api'\n\nexport const Route = createFileRoute('/posts')({\n loader: fetchPosts,\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n# Solid\n\n```tsx title=\"src/routes/posts.tsx\"\nimport { createFileRoute } from '@tanstack/solid-router'\nimport { fetchPosts } from './api'\n\nexport const Route = createFileRoute('/posts')({\n loader: fetchPosts,\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n\n\n**After (Split into two files)**\n\nThis file would contain the critical route configuration:\n\n\n\n# React\n\n```tsx title=\"src/routes/posts.tsx\"\nimport { createFileRoute } from '@tanstack/react-router'\nimport { fetchPosts } from './api'\n\nexport const Route = createFileRoute('/posts')({\n loader: fetchPosts,\n})\n```\n\n# Solid\n\n```tsx title=\"src/routes/posts.tsx\"\nimport { createFileRoute } from '@tanstack/solid-router'\nimport { fetchPosts } from './api'\n\nexport const Route = createFileRoute('/posts')({\n loader: fetchPosts,\n})\n```\n\n\n\nWith the non-critical route configuration going into the file with the `.lazy.tsx` suffix:\n\n\n\n# React\n\n```tsx title=\"src/routes/posts.lazy.tsx\"\nimport { createLazyFileRoute } from '@tanstack/react-router'\n\nexport const Route = createLazyFileRoute('/posts')({\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n# Solid\n\n```tsx title=\"src/routes/posts.lazy.tsx\"\nimport { createLazyFileRoute } from '@tanstack/solid-router'\n\nexport const Route = createLazyFileRoute('/posts')({\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n\n\n## Using Virtual Routes\n\nYou might run into a situation where you end up splitting out everything from a route file, leaving it empty! In this case, simply **delete the route file entirely**! A virtual route will automatically be generated for you to serve as an anchor for your code split files. This virtual route will live directly in the generated route tree file.\n\n**Before (Virtual Routes)**\n\n\n\n# React\n\n\n\n```tsx title=\"src/routes/posts.tsx\"\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts')({\n // Hello?\n})\n```\n\n```tsx title=\"src/routes/posts.lazy.tsx\"\nimport { createLazyFileRoute } from '@tanstack/react-router'\n\nexport const Route = createLazyFileRoute('/posts')({\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n\n\n# Solid\n\n\n\n```tsx title=\"src/routes/posts.tsx\"\nimport { createFileRoute } from '@tanstack/solid-router'\n\nexport const Route = createFileRoute('/posts')({\n // Hello?\n})\n```\n\n```tsx title=\"src/routes/posts.lazy.tsx\"\nimport { createLazyFileRoute } from '@tanstack/solid-router'\n\nexport const Route = createLazyFileRoute('/posts')({\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n\n\n\n\n**After (Virtual Routes)**\n\n\n\n# React\n\n```tsx title=\"src/routes/posts.lazy.tsx\"\nimport { createLazyFileRoute } from '@tanstack/react-router'\n\nexport const Route = createLazyFileRoute('/posts')({\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n# Solid\n\n```tsx title=\"src/routes/posts.lazy.tsx\"\nimport { createLazyFileRoute } from '@tanstack/solid-router'\n\nexport const Route = createLazyFileRoute('/posts')({\n component: Posts,\n})\n\nfunction Posts() {\n // ...\n}\n```\n\n\n\nTada! \uD83C\uDF89\n\n## Code-Based Splitting\n\nIf you are using code-based routing, you can still code-split your routes using the `Route.lazy()` method and the `createLazyRoute` function. You'll need to split your route configuration into two parts:\n\nCreate a lazy route using the `createLazyRoute` function.\n\n```tsx title=\"src/posts.lazy.tsx\"\nexport const Route = createLazyRoute('/posts')({\n component: MyComponent,\n})\n\nfunction MyComponent() {\n return
My Component
\n}\n```\n\nThen, call the `.lazy` method on the route definition in your `app.tsx` to import the lazy/code-split route with the non-critical route configuration.\n\n```tsx title=\"src/app.tsx\"\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/posts',\n}).lazy(() => import('./posts.lazy').then((d) => d.Route))\n```\n\n## Data Loader Splitting\n\n**Be warned!!!** Splitting a route loader is a dangerous game.\n\nIt can be a powerful tool to reduce bundle size, but it comes with a cost as mentioned in the [How does TanStack Router split code?](#how-does-tanstack-router-split-code) section.\n\nYou can code split your data loading logic using the Route's `loader` option. While this process makes it difficult to maintain type-safety with the parameters passed to your loader, you can always use the generic `LoaderContext` type to get you most of the way there:\n\n\n\n# React\n\n```tsx\nimport { lazyFn } from '@tanstack/react-router'\n\nconst route = createRoute({\n path: '/my-route',\n component: MyComponent,\n loader: lazyFn(() => import('./loader'), 'loader'),\n})\n\n// In another file...a\nexport const loader = async (context: LoaderContext) => {\n /// ...\n}\n```\n\n# Solid\n\n```tsx\nimport { lazyFn } from '@tanstack/solid-router'\n\nconst route = createRoute({\n path: '/my-route',\n component: MyComponent,\n loader: lazyFn(() => import('./loader'), 'loader'),\n})\n\n// In another file...a\nexport const loader = async (context: LoaderContext) => {\n /// ...\n}\n```\n\n\n\nIf you are using file-based routing, you'll only be able to split your `loader` if you are using [Automatic Code Splitting](#using-automatic-code-splitting) with customized bundling options.\n\n## Manually accessing Route APIs in other files with the `getRouteApi` helper\n\nAs you might have guessed, placing your component code in a separate file than your route can make it difficult to consume the route itself. To help with this, TanStack Router exports a handy `getRouteApi` function that you can use to access a route's type-safe APIs in a file without importing the route itself.\n\n\n\n# React\n\n\n\n```tsx title=\"src/my-route.tsx\"\nimport { createRoute } from '@tanstack/react-router'\nimport { MyComponent } from './MyComponent'\n\nconst route = createRoute({\n path: '/my-route',\n loader: () => ({\n foo: 'bar',\n }),\n component: MyComponent,\n})\n```\n\n```tsx title=\"src/MyComponent.tsx\"\nimport { getRouteApi } from '@tanstack/react-router'\n\nconst route = getRouteApi('/my-route')\n\nexport function MyComponent() {\n const loaderData = route.useLoaderData()\n // ^? { foo: string }\n\n return
\n}\n```\n\n\n\n\n\nThe `getRouteApi` function is useful for accessing other type-safe APIs:\n\n- `useLoaderData`\n- `useLoaderDeps`\n- `useMatch`\n- `useParams`\n- `useRouteContext`\n- `useSearch`\n\n# Creating a Router\n\n## The `createRouter` function\n\nWhen you're ready to start using your router, you'll need to create a new `Router` instance. The router instance is the core brains of TanStack Router and is responsible for managing the route tree, matching routes, and coordinating navigations and route transitions. It also serves as a place to configure router-wide settings.\n\n\n\n# React\n\n```tsx title=\"src/router.tsx\"\nimport { createRouter } from '@tanstack/react-router'\n\nconst router = createRouter({\n // ...\n})\n```\n\n# Solid\n\n```tsx title=\"src/router.tsx\"\nimport { createRouter } from '@tanstack/solid-router'\n\nconst router = createRouter({\n // ...\n})\n```\n\n\n\n## Route Tree\n\nYou'll probably notice quickly that the `Router` constructor requires a `routeTree` option. This is the route tree that the router will use to match routes and render components.\n\nWhether you used [file-based routing](../routing/file-based-routing.md) or [code-based routing](../routing/code-based-routing.md), you'll need to pass your route tree to the `createRouter` function:\n\n### Filesystem Route Tree\n\nIf you used our recommended file-based routing, then it's likely your generated route tree file was created at the default `src/routeTree.gen.ts` location. If you used a custom location, then you'll need to import your route tree from that location.\n\n```tsx\nimport { routeTree } from './routeTree.gen'\n```\n\n### Code-Based Route Tree\n\nIf you used code-based routing, then you likely created your route tree manually using the root route's `addChildren` method:\n\n```tsx\nconst routeTree = rootRoute.addChildren([\n // ...\n])\n```\n\n## Router Type Safety\n\n> [!IMPORTANT]\n> DO NOT SKIP THIS SECTION! \u26A0\uFE0F\n\nTanStack Router provides amazing support for TypeScript, even for things you wouldn't expect like bare imports straight from the library! To make this possible, you must register your router's types using TypeScripts' [Declaration Merging](https://www.typescriptlang.org/docs/handbook/declaration-merging.html) feature. This is done by extending the `Register` interface on `@tanstack/react-router` with a `router` property that has the type of your `router` instance:\n\n\n\n# React\n\n```tsx title=\"src/router.tsx\"\ndeclare module '@tanstack/react-router' {\n interface Register {\n // This infers the type of our router and registers it across your entire project\n router: typeof router\n }\n}\n```\n\n# Solid\n\n```tsx title=\"src/router.tsx\"\ndeclare module '@tanstack/solid-router' {\n interface Register {\n // This infers the type of our router and registers it across your entire project\n router: typeof router\n }\n}\n```\n\n\n\nWith your router registered, you'll now get type-safety across your entire project for anything related to routing.\n\n## 404 Not Found Route\n\nAs promised in earlier guides, we'll now cover the `notFoundRoute` option. This option is used to configure a route that will render when no other suitable match is found. This is useful for rendering a 404 page or redirecting to a default route.\n\nIf you are using either file-based or code-based routing, then you'll need to add a `notFoundComponent` key to `createRootRoute`:\n\n```tsx\nexport const Route = createRootRoute({\n component: () => (\n // ...\n ),\n notFoundComponent: () =>
404 Not Found
,\n});\n```\n\n## Other Options\n\nThere are many other options that can be passed to the `Router` constructor. You can find a full list of them in the [API Reference](../api/router/RouterOptionsType.md).\n\n# Custom Link\n\nWhile repeating yourself can be acceptable in many situations, you might find that you do it too often. At times, you may want to create cross-cutting components with additional behavior or styles. You might also consider using third-party libraries in combination with TanStack Router's type safety.\n\n## `createLink` for cross-cutting concerns\n\n`createLink` creates a custom `Link` component with the same type parameters as `Link`. This means you can create your own component which provides the same type safety and typescript performance as `Link`.\n\n### Basic example\n\nIf you want to create a basic custom link component, you can do so with the following:\n\n\n\n# React\n\n```tsx\nimport * as React from 'react'\nimport { createLink, LinkComponent } from '@tanstack/react-router'\n\ninterface BasicLinkProps extends React.AnchorHTMLAttributes {\n // Add any additional props you want to pass to the anchor element\n}\n\nconst BasicLinkComponent = React.forwardRef(\n (props, ref) => {\n return (\n \n )\n },\n)\n\nconst CreatedLinkComponent = createLink(BasicLinkComponent)\n\nexport const CustomLink: LinkComponent = (props) => {\n return \n}\n```\n\n# Solid\n\n```tsx\nimport * as Solid from 'solid-js'\nimport { createLink, LinkComponent } from '@tanstack/solid-router'\n\nexport const Route = createRootRoute({\n component: RootComponent,\n})\n\ntype BasicLinkProps = Solid.JSX.IntrinsicElements['a'] & {\n // Add any additional props you want to pass to the anchor element\n}\n\nconst BasicLinkComponent: Solid.Component = (props) => (\n \n {props.children}\n \n)\n\nconst CreatedLinkComponent = createLink(BasicLinkComponent)\n\nexport const CustomLink: LinkComponent = (props) => {\n return \n}\n```\n\n\n\nYou can then use your newly created `Link` component as any other `Link`\n\n```tsx\n\n```\n\n## `createLink` with third party libraries\n\nHere are some examples of how you can use `createLink` with third-party libraries.\n\n\n\n# React\n\n### React Aria Components example\n\nReact Aria Components v1.11.0 and later works with TanStack Router's `preload (intent)` prop. Use `createLink` to wrap each React Aria component that you use as a link.\n\n\n\n```tsx title=\"RACLink.tsx\"\nimport { createLink } from '@tanstack/react-router'\nimport { Link as RACLink, MenuItem } from 'react-aria-components'\n\nexport const Link = createLink(RACLink)\nexport const MenuItemLink = createLink(MenuItem)\n```\n\n```tsx title=\"CustomRACLink.tsx\"\nimport { createLink } from '@tanstack/react-router'\nimport { Link as RACLink, type LinkProps } from 'react-aria-components'\n\ninterface MyLinkProps extends LinkProps {\n // your props\n}\n\nfunction MyLink(props: MyLinkProps) {\n return (\n ({\n color: isHovered ? 'red' : 'blue',\n })}\n />\n )\n}\n\nexport const Link = createLink(MyLink)\n```\n\n\n\nTo use React Aria's render props, including the `className`, `style`, and `children` functions, create a wrapper component and pass that to `createLink`.\n\n\n\n\n\n# React\n\n### Chakra UI example\n\n```tsx title=\"ChakraLinkComponent.tsx\"\nimport * as React from 'react'\nimport { createLink, LinkComponent } from '@tanstack/react-router'\nimport { Link } from '@chakra-ui/react'\n\ninterface ChakraLinkProps extends Omit<\n React.ComponentPropsWithoutRef,\n 'href'\n> {\n // Add any additional props you want to pass to the link\n}\n\nconst ChakraLinkComponent = React.forwardRef<\n HTMLAnchorElement,\n ChakraLinkProps\n>((props, ref) => {\n return \n})\n\nconst CreatedLinkComponent = createLink(ChakraLinkComponent)\n\nexport const CustomLink: LinkComponent = (\n props,\n) => {\n return (\n \n )\n}\n```\n\n\n\n\n\n# React\n\n### MUI example\n\nThere is an [example](https://github.com/TanStack/router/tree/main/examples/react/start-material-ui) available which uses these patterns.\n\n#### `Link`\n\nIf the MUI `Link` should simply behave like the router `Link`, it can be just wrapped with `createLink`:\n\n\n\n```tsx title=\"CustomLink.tsx\"\nimport { createLink } from '@tanstack/react-router'\nimport { Link } from '@mui/material'\n\nexport const CustomLink = createLink(Link)\n```\n\n\n\nIf the `Link` should be customized this approach can be used:\n\n\n\n```tsx title=\"CustomLink.tsx\"\nimport React from 'react'\nimport { createLink } from '@tanstack/react-router'\nimport { Link } from '@mui/material'\nimport type { LinkProps } from '@mui/material'\nimport type { LinkComponent } from '@tanstack/react-router'\n\ninterface MUILinkProps extends LinkProps {\n // Add any additional props you want to pass to the Link\n}\n\nconst MUILinkComponent = React.forwardRef(\n (props, ref) => ,\n)\n\nconst CreatedLinkComponent = createLink(MUILinkComponent)\n\nexport const CustomLink: LinkComponent = (props) => {\n return \n}\n\n// Can also be styled\n```\n\n\n\n#### `Button`\n\nIf a `Button` should be used as a router `Link`, the `component` should be set as `a`:\n\n\n\n```tsx title=\"CustomButtonLink.tsx\"\nimport React from 'react'\nimport { createLink } from '@tanstack/react-router'\nimport { Button } from '@mui/material'\nimport type { ButtonProps } from '@mui/material'\nimport type { LinkComponent } from '@tanstack/react-router'\n\ninterface MUIButtonLinkProps extends ButtonProps<'a'> {\n // Add any additional props you want to pass to the Button\n}\n\nconst MUIButtonLinkComponent = React.forwardRef<\n HTMLAnchorElement,\n MUIButtonLinkProps\n>((props, ref) => )\n\nconst CreatedButtonLinkComponent = createLink(MUIButtonLinkComponent)\n\nexport const CustomButtonLink: LinkComponent = (\n props,\n) => {\n return \n}\n```\n\n\n\n#### Usage with `styled`\n\nAny of these MUI approaches can then be used with `styled`:\n\n\n\n```tsx title=\"StyledCustomLink.tsx\"\nimport { css, styled } from '@mui/material'\nimport { CustomLink } from './CustomLink'\n\nconst StyledCustomLink = styled(CustomLink)(\n ({ theme }) => css`\n color: ${theme.palette.common.white};\n `,\n)\n```\n\n\n\n\n\n\n\n# React\n\n### Mantine example\n\n\n\n```tsx title=\"CustomLink.tsx\"\nimport * as React from 'react'\nimport { createLink, LinkComponent } from '@tanstack/react-router'\nimport { Anchor, AnchorProps } from '@mantine/core'\n\ninterface MantineAnchorProps extends Omit {\n // Add any additional props you want to pass to the anchor\n}\n\nconst MantineLinkComponent = React.forwardRef<\n HTMLAnchorElement,\n MantineAnchorProps\n>((props, ref) => {\n return \n})\n\nconst CreatedLinkComponent = createLink(MantineLinkComponent)\n\nexport const CustomLink: LinkComponent = (\n props,\n) => {\n return \n}\n```\n\n\n\n\n\n\n\n# Solid\n\n### Some Library example\n\n\n\n```tsx title=\"UntitledLink.tsx\"\n// TODO: Add this example.\n```\n\n\n\n\n\n# Custom Search Param Serialization\n\nBy default, TanStack Router parses and serializes your URL Search Params automatically using `JSON.stringify` and `JSON.parse`. This process involves escaping and unescaping the search string, which is a common practice for URL search params, in addition to the serialization and deserialization of the search object.\n\nFor instance, using the default configuration, if you have the following search object:\n\n```tsx\nconst search = {\n page: 1,\n sort: 'asc',\n filters: { author: 'tanner', min_words: 800 },\n}\n```\n\nIt would be serialized and escaped into the following search string:\n\n```txt\n?page=1&sort=asc&filters=%7B%22author%22%3A%22tanner%22%2C%22min_words%22%3A800%7D\n```\n\nWe can implement the default behavior with the following code:\n\n\n\n# React\n\n```tsx\nimport {\n createRouter,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/react-router'\n\nconst router = createRouter({\n // ...\n parseSearch: parseSearchWith(JSON.parse),\n stringifySearch: stringifySearchWith(JSON.stringify),\n})\n```\n\n# Solid\n\n```tsx\nimport {\n createRouter,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/solid-router'\n\nconst router = createRouter({\n // ...\n parseSearch: parseSearchWith(JSON.parse),\n stringifySearch: stringifySearchWith(JSON.stringify),\n})\n```\n\n\n\nHowever, this default behavior may not be suitable for all use cases. For example, you may want to use a different serialization format, such as base64 encoding, or you may want to use a purpose-built serialization/deserialization library, like [query-string](https://github.com/sindresorhus/query-string), [JSURL2](https://github.com/wmertens/jsurl2), or [Zipson](https://jgranstrom.github.io/zipson/).\n\nThis can be achieved by providing your own serialization and deserialization functions to the `parseSearch` and `stringifySearch` options in the [`Router`](../api/router/RouterOptionsType.md#stringifysearch-method) configuration. When doing this, you can utilize TanStack Router's built-in helper functions, `parseSearchWith` and `stringifySearchWith`, to simplify the process.\n\n> [!TIP]\n> An important aspect of serialization and deserialization, is that you are able to get the same object back after deserialization. This is important because if the serialization and deserialization process is not done correctly, you may lose some information. For example, if you are using a library that does not support nested objects, you may lose the nested object when deserializing the search string.\n\n\n\nHere are some examples of how you can customize the search param serialization in TanStack Router:\n\n## Using Base64\n\nIt's common to base64 encode your search params to achieve maximum compatibility across browsers and URL unfurlers, etc. This can be done with the following code:\n\n\n\n# React\n\n```tsx\nimport {\n Router,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/react-router'\n\nconst router = createRouter({\n parseSearch: parseSearchWith((value) => JSON.parse(decodeFromBinary(value))),\n stringifySearch: stringifySearchWith((value) =>\n encodeToBinary(JSON.stringify(value)),\n ),\n})\n\nfunction decodeFromBinary(str: string): string {\n return decodeURIComponent(\n Array.prototype.map\n .call(atob(str), function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join(''),\n )\n}\n\nfunction encodeToBinary(str: string): string {\n return btoa(\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {\n return String.fromCharCode(parseInt(p1, 16))\n }),\n )\n}\n```\n\n# Solid\n\n```tsx\nimport {\n Router,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/solid-router'\n\nconst router = createRouter({\n parseSearch: parseSearchWith((value) => JSON.parse(decodeFromBinary(value))),\n stringifySearch: stringifySearchWith((value) =>\n encodeToBinary(JSON.stringify(value)),\n ),\n})\n\nfunction decodeFromBinary(str: string): string {\n return decodeURIComponent(\n Array.prototype.map\n .call(atob(str), function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join(''),\n )\n}\n\nfunction encodeToBinary(str: string): string {\n return btoa(\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {\n return String.fromCharCode(parseInt(p1, 16))\n }),\n )\n}\n```\n\n\n\n> [\u26A0\uFE0F Why does this snippet not use atob/btoa?](#safe-binary-encodingdecoding)\n\nSo, if we were to turn the previous object into a search string using this configuration, it would look like this:\n\n```txt\n?page=1&sort=asc&filters=eyJhdXRob3IiOiJ0YW5uZXIiLCJtaW5fd29yZHMiOjgwMH0%3D\n```\n\n> [!WARNING]\n> If you are serializing user input into Base64, you run the risk of causing a collision with the URL deserialization. This can lead to unexpected behavior, such as the URL not being parsed correctly or being interpreted as a different value. To avoid this, you should encode the search params using a safe binary encoding/decoding method (see below).\n\n## Using the query-string library\n\nThe [query-string](https://github.com/sindresorhus/query-string) library is a popular for being able to reliably parse and stringify query strings. You can use it to customize the serialization format of your search params. This can be done with the following code:\n\n\n\n# React\n\n```tsx\nimport { createRouter } from '@tanstack/react-router'\nimport qs from 'query-string'\n\nconst router = createRouter({\n // ...\n stringifySearch: stringifySearchWith((value) =>\n qs.stringify(value, {\n // ...options\n }),\n ),\n parseSearch: parseSearchWith((value) =>\n qs.parse(value, {\n // ...options\n }),\n ),\n})\n```\n\n# Solid\n\n```tsx\nimport { createRouter } from '@tanstack/solid-router'\nimport qs from 'query-string'\n\nconst router = createRouter({\n // ...\n stringifySearch: stringifySearchWith((value) =>\n qs.stringify(value, {\n // ...options\n }),\n ),\n parseSearch: parseSearchWith((value) =>\n qs.parse(value, {\n // ...options\n }),\n ),\n})\n```\n\n\n\nSo, if we were to turn the previous object into a search string using this configuration, it would look like this:\n\n```txt\n?page=1&sort=asc&filters=author%3Dtanner%26min_words%3D800\n```\n\n## Using the JSURL2 library\n\n[JSURL2](https://github.com/wmertens/jsurl2) is a non-standard library that can compress URLs while still maintaining readability. This can be done with the following code:\n\n\n\n# React\n\n```tsx\nimport {\n Router,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/react-router'\nimport { parse, stringify } from 'jsurl2'\n\nconst router = createRouter({\n // ...\n parseSearch: parseSearchWith(parse),\n stringifySearch: stringifySearchWith(stringify),\n})\n```\n\n# Solid\n\n```tsx\nimport {\n Router,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/solid-router'\nimport { parse, stringify } from 'jsurl2'\n\nconst router = createRouter({\n // ...\n parseSearch: parseSearchWith(parse),\n stringifySearch: stringifySearchWith(stringify),\n})\n```\n\n\n\nSo, if we were to turn the previous object into a search string using this configuration, it would look like this:\n\n```txt\n?page=1&sort=asc&filters=(author~tanner~min*_words~800)~\n```\n\n## Using the Zipson library\n\n[Zipson](https://jgranstrom.github.io/zipson/) is a very user-friendly and performant JSON compression library (both in runtime performance and the resulting compression performance). To compress your search params with it (which requires escaping/unescaping and base64 encoding/decoding them as well), you can use the following code:\n\n\n\n# React\n\n```tsx\nimport {\n Router,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/react-router'\nimport { stringify, parse } from 'zipson'\n\nconst router = createRouter({\n parseSearch: parseSearchWith((value) => parse(decodeFromBinary(value))),\n stringifySearch: stringifySearchWith((value) =>\n encodeToBinary(stringify(value)),\n ),\n})\n\nfunction decodeFromBinary(str: string): string {\n return decodeURIComponent(\n Array.prototype.map\n .call(atob(str), function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join(''),\n )\n}\n\nfunction encodeToBinary(str: string): string {\n return btoa(\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {\n return String.fromCharCode(parseInt(p1, 16))\n }),\n )\n}\n```\n\n# Solid\n\n```tsx\nimport {\n Router,\n parseSearchWith,\n stringifySearchWith,\n} from '@tanstack/solid-router'\nimport { stringify, parse } from 'zipson'\n\nconst router = createRouter({\n parseSearch: parseSearchWith((value) => parse(decodeFromBinary(value))),\n stringifySearch: stringifySearchWith((value) =>\n encodeToBinary(stringify(value)),\n ),\n})\n\nfunction decodeFromBinary(str: string): string {\n return decodeURIComponent(\n Array.prototype.map\n .call(atob(str), function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join(''),\n )\n}\n\nfunction encodeToBinary(str: string): string {\n return btoa(\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {\n return String.fromCharCode(parseInt(p1, 16))\n }),\n )\n}\n```\n\n\n\n> [\u26A0\uFE0F Why does this snippet not use atob/btoa?](#safe-binary-encodingdecoding)\n\nSo, if we were to turn the previous object into a search string using this configuration, it would look like this:\n\n```txt\n?page=1&sort=asc&filters=JTdCJUMyJUE4YXV0aG9yJUMyJUE4JUMyJUE4dGFubmVyJUMyJUE4JUMyJUE4bWluX3dvcmRzJUMyJUE4JUMyJUEyQ3UlN0Q%3D\n```\n\n\n\n## Safe Binary Encoding/Decoding\n\nIn the browser, the `atob` and `btoa` functions are not guaranteed to work properly with non-UTF8 characters. We recommend using these encoding/decoding utilities instead:\n\nTo encode from a string to a binary string:\n\n```ts\nexport function encodeToBinary(str: string): string {\n return btoa(\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {\n return String.fromCharCode(parseInt(p1, 16))\n }),\n )\n}\n```\n\nTo decode from a binary string to a string:\n\n```ts\nexport function decodeFromBinary(str: string): string {\n return decodeURIComponent(\n Array.prototype.map\n .call(atob(str), function (c) {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)\n })\n .join(''),\n )\n}\n```\n\n# Data Loading\n\nData loading is a common concern for web applications and is related to routing. When loading a page for your app, it's ideal if all of the page's async requirements are fetched and fulfilled as early as possible, in parallel. The router is the best place to coordinate these async dependencies as it's usually the only place in your app that knows where users are headed before content is rendered.\n\nYou may be familiar with `getServerSideProps` from Next.js or `loader`s from Remix/React-Router. TanStack Router has similar functionality to preload/load assets on a per-route basis in parallel allowing it to render as quickly as possible as it fetches via suspense.\n\nBeyond these normal expectations of a router, TanStack Router goes above and beyond and provides **built-in SWR Caching**, a long-term in-memory caching layer for route loaders. This means that you can use TanStack Router to both preload data for your routes so they load instantaneously or temporarily cache route data for previously visited routes to use again later.\n\n## The route loading lifecycle\n\nEvery time a URL/history update is detected, the router executes the following sequence:\n\n- Route Matching (Top-Down)\n - `route.params.parse`\n - `route.validateSearch`\n- Route Pre-Loading (Serial)\n - `route.beforeLoad`\n - `route.onError`\n - `route.errorComponent` / `parentRoute.errorComponent` / `router.defaultErrorComponent`\n- Route Loading (Parallel)\n - `route.component.preload?`\n - `route.loader`\n - `route.pendingComponent` (Optional)\n - `route.component`\n - `route.onError`\n - `route.errorComponent` / `parentRoute.errorComponent` / `router.defaultErrorComponent`\n\n## To Router Cache or not to Router Cache?\n\nThere is a high possibility that TanStack's router cache will be a good fit for most smaller to medium size applications, but it's important to understand the tradeoffs of using it vs a more robust caching solution like TanStack Query:\n\nTanStack Router Cache Pros:\n\n- Built-in, easy to use, no extra dependencies\n- Handles deduping, preloading, loading, stale-while-revalidate, background refetching on a per-route basis\n- Coarse invalidation (invalidate all routes and cache at once)\n- Automatic garbage collection\n- Works great for apps that share little data between routes\n- \"Just works\" for SSR\n\nTanStack Router Cache Cons:\n\n- No persistence adapters/model\n- No shared caching/deduping between routes\n- No built-in mutation APIs (a basic `useMutation` hook is provided in many examples that may be sufficient for many use cases)\n- No built-in cache-level optimistic update APIs (you can still use ephemeral state from something like a `useMutation` hook to achieve this at the component level)\n\n> [!TIP]\n> If you know right away that you'd like to or need to use something more robust like TanStack Query, skip to the [External Data Loading](./external-data-loading.md) guide.\n\n## Using the Router Cache\n\nThe router cache is built-in and is as easy as returning data from any route's `loader` function. Let's learn how!\n\n## Route `loader`s\n\nRoute `loader` functions are called when a route match is loaded. They are called with a single parameter which is an object containing many helpful properties. We'll go over those in a bit, but first, let's look at the two supported `loader` forms:\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n})\n```\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: {\n handler: () => fetchPosts(),\n },\n})\n```\n\nUse the object form when you want to configure loader-specific behavior such as `staleReloadMode`.\n\n## `loader` Parameters\n\nThe `loader` function receives a single object with the following properties:\n\n- `abortController` - The route's abortController. Its signal is cancelled when the route is unloaded or when the Route is no longer relevant and the current invocation of the `loader` function becomes outdated.\n- `cause` - The cause of the current route match. Can be either one of the following:\n - `enter` - When the route is matched and loaded after not being matched in the previous location.\n - `preload` - When the route is being preloaded.\n - `stay` - When the route is matched and loaded after being matched in the previous location.\n- `context` - The route's context object, which is a merged union of:\n - Parent route context\n - This route's context as provided by the `beforeLoad` option\n- `deps` - The object value returned from the `Route.loaderDeps` function. If `Route.loaderDeps` is not defined, an empty object will be provided instead.\n- `location` - The current location\n- `params` - The route's path params\n- `parentMatchPromise` - `Promise` (`undefined` for the root route)\n- `preload` - Boolean which is `true` when the route is being preloaded instead of loaded\n- `route` - The route itself\n\nUsing these parameters, we can do a lot of cool things, but first, let's take a look at how we can control it and when the `loader` function is called.\n\n## Consuming data from `loader`s\n\nTo consume data from a `loader`, use the `useLoaderData` hook defined on your Route object.\n\n```tsx\nconst posts = Route.useLoaderData()\n```\n\nIf you don't have ready access to your route object (i.e. you're deep in the component tree for the current route), you can use `getRouteApi` to access the same hook (as well as the other hooks on the Route object). This should be preferred over importing the Route object, which is likely to create circular dependencies.\n\n\n\n# React\n\n```tsx\nimport { getRouteApi } from '@tanstack/react-router'\n\n// in your component\n\nconst routeApi = getRouteApi('/posts')\nconst data = routeApi.useLoaderData()\n```\n\n# Solid\n\n```tsx\nimport { getRouteApi } from '@tanstack/solid-router'\n\n// in your component\n\nconst routeApi = getRouteApi('/posts')\nconst data = routeApi.useLoaderData()\n```\n\n\n\n## Dependency-based Stale-While-Revalidate Caching\n\nTanStack Router provides a built-in Stale-While-Revalidate caching layer for route loaders that is keyed on the dependencies of a route:\n\n- The route's fully parsed pathname\n - e.g. `/posts/1` vs `/posts/2`\n- Any additional dependencies provided by the `loaderDeps` option\n - e.g. `loaderDeps: ({ search: { pageIndex, pageSize } }) => ({ pageIndex, pageSize })`\n\nUsing these dependencies as keys, TanStack Router will cache the data returned from a route's `loader` function and use it to fulfill subsequent requests for the same route match. This means that if a route's data is already in the cache, it will be returned immediately, then **potentially** be refetched in the background depending on the \"freshness\" of the data.\n\n### Key options\n\nTo control router dependencies and \"freshness\", TanStack Router provides a plethora of options to control the keying and caching behavior of your route loaders. Let's take a look at them in the order that you are most likely to use them:\n\n- `routeOptions.loaderDeps`\n - A function that supplies you the search params for a router and returns an object of dependencies for use in your `loader` function. When these deps changed from navigation to navigation, it will cause the route to reload regardless of `staleTime`s. The deps are compared using a deep equality check.\n- `routeOptions.staleTime`\n- `routerOptions.defaultStaleTime`\n - The number of milliseconds that a route's data should be considered fresh when attempting to load.\n- `routeOptions.preloadStaleTime`\n- `routerOptions.defaultPreloadStaleTime`\n - The number of milliseconds that a route's data should be considered fresh attempting to preload.\n- `routeOptions.gcTime`\n- `routerOptions.defaultGcTime`\n - The number of milliseconds that a route's data should be kept in the cache before being garbage collected.\n- `routeOptions.shouldReload`\n - A function that receives the same `beforeLoad` and `loaderContext` parameters and returns a boolean indicating if the route should reload. This offers one more level of control over when a route should reload beyond `staleTime` and `loaderDeps` and can be used to implement patterns similar to Remix's `shouldLoad` option.\n- `routeOptions.loader.staleReloadMode`\n- `routerOptions.defaultStaleReloadMode`\n - Controls what happens when a matched route already has stale successful data. Use `'background'` for stale-while-revalidate, or `'blocking'` to wait for the stale loader reload to finish before continuing.\n\n### \u26A0\uFE0F Some Important Defaults\n\n- By default, the `staleTime` is set to `0`, meaning that the route's data is immediately considered stale. Stale matches are reloaded in the background when the route is entered again, when its loader key changes (path params used by the route or `loaderDeps`), or when `router.load()` is called explicitly.\n- By default, a previously preloaded route is considered fresh for **30 seconds**. This means if a route is preloaded, then preloaded again within 30 seconds, the second preload will be ignored. This prevents unnecessary preloads from happening too frequently. **When a route is loaded normally, the standard `staleTime` is used.**\n- By default, the `gcTime` is set to **30 minutes**, meaning that any route data that has not been accessed in 30 minutes will be garbage collected and removed from the cache.\n- By default, `staleReloadMode` is `'background'`, so stale successful matches keep rendering with their existing `loaderData` while the loader revalidates in the background.\n- `router.invalidate()` will force all active routes to reload their loaders immediately and mark every cached route's data as stale.\n\n### Using `loaderDeps` to access search params\n\nImagine a `/posts` route supports some pagination via search params `offset` and `limit`. For the cache to uniquely store this data, we need to access these search params via the `loaderDeps` function. By explicitly identifying them, each route match for `/posts` with different `offset` and `limit` won't get mixed up!\n\nOnce we have these deps in place, the route will always reload when the deps change.\n\n```tsx\n// /routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loaderDeps: ({ search: { offset, limit } }) => ({ offset, limit }),\n loader: ({ deps: { offset, limit } }) =>\n fetchPosts({\n offset,\n limit,\n }),\n})\n```\n\n> [!WARNING]\n> **Only include dependencies you actually use in the loader.**\n>\n> A common mistake is returning the entire `search` object:\n>\n> ```tsx\n> // \u274C Don't do this - causes unnecessary cache invalidation\n> loaderDeps: ({ search }) => search,\n> loader: ({ deps }) => fetchPosts({ page: deps.page }), // only uses page!\n> ```\n>\n> This causes the route to reload whenever ANY search param changes, even params not used in the loader (like `viewMode` or `sortDirection`). Instead, extract only what you need:\n>\n> ```tsx\n> // \u2705 Do this - only reload when used params change\n> loaderDeps: ({ search }) => ({\n> page: search.page,\n> limit: search.limit,\n> }),\n> loader: ({ deps }) => fetchPosts(deps),\n> ```\n\n### Using `staleTime` to control how long data is considered fresh\n\nBy default, `staleTime` for navigations is set to `0`ms (and 30 seconds for preloads) which means that the route's data will always be considered stale. When a stale route is entered again, its loader key changes, or `router.load()` is called explicitly, the route will reload in the background.\n\n**This is a good default for most use cases, but you may find that some route data is more static or potentially expensive to load.** In these cases, you can use the `staleTime` option to control how long the route's data is considered fresh for navigations. Let's take a look at an example:\n\n```tsx\n// /routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n // Consider the route's data fresh for 10 seconds\n staleTime: 10_000,\n})\n```\n\nBy passing `10_000` to the `staleTime` option, we are telling the router to consider the route's data fresh for 10 seconds. This means that if the user navigates to `/posts` from `/about` within 10 seconds of the last loader result, the route's data will not be reloaded. If the user then navigates to `/posts` from `/about` after 10 seconds, the route's data will be reloaded **in the background**.\n\n## Choosing background vs blocking stale reloads\n\nBy default, stale successful matches use stale-while-revalidate behavior. That means the router can render with the existing `loaderData` immediately and then refresh it in the background.\n\nIf you want a specific loader to wait for a stale reload to finish before continuing, use the object form and set `staleReloadMode: 'blocking'`:\n\n```tsx\n// /routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: {\n handler: () => fetchPosts(),\n staleReloadMode: 'blocking',\n },\n})\n```\n\nYou can also change the default for the entire router:\n\n```tsx\nconst router = createRouter({\n routeTree,\n defaultStaleReloadMode: 'blocking',\n})\n```\n\nUse `'background'` when showing stale data during revalidation is acceptable. Use `'blocking'` when you want stale matches to behave more like a fresh load and wait for the new loader result.\n\n## Turning off automatic stale reloads\n\nTo disable automatic stale reloads for a route, set the `staleTime` option to `Infinity`:\n\n```tsx\n// /routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n staleTime: Infinity,\n})\n```\n\nYou can even turn this off for all routes by setting the `defaultStaleTime` option on the router:\n\n```tsx\nconst router = createRouter({\n routeTree,\n defaultStaleTime: Infinity,\n})\n```\n\nThis differs from `staleReloadMode: 'blocking'`:\n\n- `staleTime: Infinity` prevents the route from becoming stale in the first place\n- `staleReloadMode: 'blocking'` still allows stale reloads, but waits for them instead of doing them in the background\n\n## Using `shouldReload` and `gcTime` to opt-out of caching\n\nSimilar to Remix's default functionality, you may want to configure a route to only load on entry or when critical loader deps change. You can do this by using the `gcTime` option combined with the `shouldReload` option, which accepts either a `boolean` or a function that receives the same `beforeLoad` and `loaderContext` parameters and returns a boolean indicating if the route should reload.\n\n```tsx\n// /routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loaderDeps: ({ search: { offset, limit } }) => ({ offset, limit }),\n loader: ({ deps }) => fetchPosts(deps),\n // Do not cache this route's data after it's unloaded\n gcTime: 0,\n // Only reload the route when the user navigates to it or when deps change\n shouldReload: false,\n})\n```\n\n### Opting out of caching while still preloading\n\nEven though you may opt-out of short-term caching for your route data, you can still get the benefits of preloading! With the above configuration, preloading will still \"just work\" with the default `preloadGcTime`. This means that if a route is preloaded, then navigated to, the route's data will be considered fresh and will not be reloaded.\n\nTo opt out of preloading, don't turn it on via the `routerOptions.defaultPreload` or `routeOptions.preload` options.\n\n## Passing all loader events to an external cache\n\nWe break down this use case in the [External Data Loading](./external-data-loading.md) page, but if you'd like to use an external cache like TanStack Query, you can do so by passing all loader events to your external cache. As long as you are using the defaults, the only change you'll need to make is to set the `defaultPreloadStaleTime` option on the router to `0`:\n\n```tsx\nconst router = createRouter({\n routeTree,\n defaultPreloadStaleTime: 0,\n})\n```\n\nThis will ensure that every preload, load, and reload event will trigger your `loader` functions, which can then be handled and deduped by your external cache.\n\n## Using Router Context\n\nThe `context` argument passed to the `loader` function is an object containing a merged union of:\n\n- Parent route context\n- This route's context as provided by the `beforeLoad` option\n\nStarting at the very top of the router, you can pass an initial context to the router via the `context` option. This context will be available to all routes in the router and get copied and extended by each route as they are matched. This happens by passing a context to a route via the `beforeLoad` option. This context will be available to all the route's child routes. The resulting context will be available to the route's `loader` function.\n\nIn this example, we'll create a function in our route context to fetch posts, then use it in our `loader` function.\n\n> \uD83E\uDDE0 Context is a powerful tool for dependency injection. You can use it to inject services, hooks, and other objects into your router and routes. You can also additively pass data down the route tree at every route using a route's `beforeLoad` option.\n\n- `/utils/fetchPosts.tsx`\n\n```tsx\nexport const fetchPosts = async () => {\n const res = await fetch(`/api/posts?page=${pageIndex}`)\n if (!res.ok) throw new Error('Failed to fetch posts')\n return res.json()\n}\n```\n\n- `/routes/__root.tsx`\n\n\n\n# React\n\n```tsx\nimport { createRootRouteWithContext } from '@tanstack/react-router'\n\n// Create a root route using the createRootRouteWithContext<{...}>() function and pass it whatever types you would like to be available in your router context.\nexport const Route = createRootRouteWithContext<{\n fetchPosts: typeof fetchPosts\n}>()() // NOTE: the double call is on purpose, since createRootRouteWithContext is a factory ;)\n```\n\n# Solid\n\n```tsx\nimport { createRootRouteWithContext } from '@tanstack/solid-router'\n\n// Create a root route using the createRootRouteWithContext<{...}>() function and pass it whatever types you would like to be available in your router context.\nexport const Route = createRootRouteWithContext<{\n fetchPosts: typeof fetchPosts\n}>()() // NOTE: the double call is on purpose, since createRootRouteWithContext is a factory ;)\n```\n\n\n\n- `/routes/posts.tsx`\n\n```tsx\n// Notice how our postsRoute references context to get our fetchPosts function\n// This can be a powerful tool for dependency injection across your router\n// and routes.\nexport const Route = createFileRoute('/posts')({\n loader: ({ context: { fetchPosts } }) => fetchPosts(),\n})\n```\n\n- `/router.tsx`\n\n```tsx\nimport { routeTree } from './routeTree.gen'\n\n// Use your routerContext to create a new router\n// This will require that you fullfil the type requirements of the routerContext\nconst router = createRouter({\n routeTree,\n context: {\n // Supply the fetchPosts function to the router context\n fetchPosts,\n },\n})\n```\n\n## Using Path Params\n\nTo use path params in your `loader` function, access them via the `params` property on the function's parameters. Here's an example:\n\n```tsx\n// src/routes/posts.$postId.tsx\nexport const Route = createFileRoute('/posts/$postId')({\n loader: ({ params: { postId } }) => fetchPostById(postId),\n})\n```\n\n## Using Route Context\n\nPassing down global context to your router is great, but what if you want to provide context that is specific to a route? This is where the `beforeLoad` option comes in. The `beforeLoad` option is a function that runs right before attempting to load a route and receives the same parameters as `loader`. Beyond its ability to redirect potential matches, block loader requests, etc, it can also return an object that will be merged into the route's context. Let's take a look at an example where we inject some data into our route context via the `beforeLoad` option:\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n // Pass the fetchPosts function to the route context\n beforeLoad: () => ({\n fetchPosts: () => console.info('foo'),\n }),\n loader: ({ context: { fetchPosts } }) => {\n fetchPosts() // 'foo'\n\n // ...\n },\n})\n```\n\n## Using Search Params in Loaders\n\n> \u2753 But wait Tanner... where the heck are my search params?!\n\nYou might be here wondering why `search` isn't directly available in the `loader` function's parameters. We've purposefully designed it this way to help you succeed. Let's take a look at why:\n\n- Search Parameters being used in a loader function are a very good indicator that those search params should also be used to uniquely identify the data being loaded. For example, you may have a route that uses a search param like `pageIndex` that uniquely identifies the data held inside of the route match. Or, imagine a `/users/user` route that uses the search param `userId` to identify a specific user in your application, you might model your url like this: `/users/user?userId=123`. This means that your `user` route would need some extra help to identify a specific user.\n- Directly accessing search params in a loader function can lead to bugs in caching and preloading where the data being loaded is not unique to the current URL pathname and search params. For example, you might ask your `/posts` route to preload page 2's results, but without the distinction of pages in your route configuration, you will end up fetching, storing and displaying page 2's data on your `/posts` or `?page=1` screen instead of it preloading in the background!\n- Placing a threshold between search parameters and the loader function allows the router to understand your dependencies and reactivity.\n\n```tsx\n// /routes/users.user.tsx\nexport const Route = createFileRoute('/users/user')({\n validateSearch: (search) =>\n search as {\n userId: string\n },\n loaderDeps: ({ search: { userId } }) => ({\n userId,\n }),\n loader: async ({ deps: { userId } }) => getUser(userId),\n})\n```\n\n### Accessing Search Params via `routeOptions.loaderDeps`\n\n```tsx\n// /routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n // Use zod to validate and parse the search params\n validateSearch: z.object({\n offset: z.number().int().nonnegative().catch(0),\n }),\n // Pass the offset to your loader deps via the loaderDeps function\n loaderDeps: ({ search: { offset } }) => ({ offset }),\n // Use the offset from context in the loader function\n loader: async ({ deps: { offset } }) =>\n fetchPosts({\n offset,\n }),\n})\n```\n\n## Using the Abort Signal\n\nThe `abortController` property of the `loader` function is an [AbortController](https://developer.mozilla.org/en-US/docs/Web/API/AbortController). Its signal is cancelled when the route is unloaded or when the `loader` call becomes outdated. This is useful for cancelling network requests when the route is unloaded or when the route's params change. Here is an example using it with a fetch call:\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: ({ abortController }) =>\n fetchPosts({\n // Pass this to an underlying fetch call or anything that supports signals\n signal: abortController.signal,\n }),\n})\n```\n\n## Using the `preload` flag\n\nThe `preload` property of the `loader` function is a boolean which is `true` when the route is being preloaded instead of loaded. Some data loading libraries may handle preloading differently than a standard fetch, so you may want to pass `preload` to your data loading library, or use it to execute the appropriate data loading logic:\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: async ({ preload }) =>\n fetchPosts({\n maxAge: preload ? 10_000 : 0, // Preloads should hang around a bit longer\n }),\n})\n```\n\n## Handling Slow Loaders\n\nIdeally most route loaders can resolve their data within a short moment, removing the need to render a placeholder spinner and simply rely on suspense to render the next route when it's completely ready. When critical data that is required to render a route's component is slow though, you have 2 options:\n\n- Split up your fast and slow data into separate promises and `defer` the slow data until after the fast data is loaded (see the [Deferred Data Loading](./deferred-data-loading.md) guide).\n- Show a pending component after an optimistic suspense threshold until all of the data is ready (See below).\n\n## Showing a pending component\n\n**By default, TanStack Router will show a pending component for loaders that take longer than 1 second to resolve.** This is an optimistic threshold that can be configured via:\n\n- `routeOptions.pendingMs` or\n- `routerOptions.defaultPendingMs`\n\nWhen the pending time threshold is exceeded, the router will render the `pendingComponent` option of the route, if configured.\n\n## Avoiding Pending Component Flash\n\nIf you're using a pending component, the last thing you want is for your pending time threshold to be met, then have your data resolve immediately after, resulting in a jarring flash of your pending component. To avoid this, **TanStack Router by default will show your pending component for at least 500ms**. This is an optimistic threshold that can be configured via:\n\n- `routeOptions.pendingMinMs` or\n- `routerOptions.defaultPendingMinMs`\n\n## Handling Errors\n\nTanStack Router provides a few ways to handle errors that occur during the route loading lifecycle. Let's take a look at them.\n\n### Handling Errors with `routeOptions.onError`\n\nThe `routeOptions.onError` option is a function that is called when an error occurs during the route loading.\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n onError: ({ error }) => {\n // Log the error\n console.error(error)\n },\n})\n```\n\n### Handling Errors with `routeOptions.onCatch`\n\nThe `routeOptions.onCatch` option is a function that is called whenever an error was caught by the router's CatchBoundary.\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n onCatch: ({ error, errorInfo }) => {\n // Log the error\n console.error(error)\n },\n})\n```\n\n### Handling Errors with `routeOptions.errorComponent`\n\nThe `routeOptions.errorComponent` option is a component that is rendered when an error occurs during the route loading or rendering lifecycle. It is rendered with the following props:\n\n- `error` - The error that occurred\n- `reset` - A function to reset the internal `CatchBoundary`\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n errorComponent: ({ error }) => {\n // Render an error message\n return
{error.message}
\n },\n})\n```\n\nThe `reset` function can be used to allow the user to retry rendering the error boundaries normal children:\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n errorComponent: ({ error, reset }) => {\n return (\n
\n {error.message}\n \n
\n )\n },\n})\n```\n\nIf the error was the result of a route load, you should instead call `router.invalidate()`, which will coordinate both a router reload and an error boundary reset:\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n errorComponent: ({ error, reset }) => {\n const router = useRouter()\n\n return (\n
\n {error.message}\n \n
\n )\n },\n})\n```\n\n### Using the default `ErrorComponent`\n\nTanStack Router provides a default `ErrorComponent` that is rendered when an error occurs during the route loading or rendering lifecycle. If you choose to override your routes' error components, it's still wise to always fall back to rendering any uncaught errors with the default `ErrorComponent`:\n\n```tsx\n// src/routes/posts.tsx\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n errorComponent: ({ error }) => {\n if (error instanceof MyCustomError) {\n // Render a custom error message\n return
{error.message}
\n }\n\n // Fallback to the default ErrorComponent\n return \n },\n})\n```\n\n# Data Mutations\n\nSince TanStack router does not store or cache data, it's role in data mutation is slim to none outside of reacting to potential URL side-effects from external mutation events. That said, we've compiled a list of mutation-related features you might find useful and libraries that implement them.\n\nLook for and use mutation utilities that support:\n\n- Handling and caching submission state\n- Providing both local and global optimistic UI support\n- Built-in hooks to wire up invalidation (or automatically support it)\n- Handling multiple in-flight mutations at once\n- Organizing mutation state as a globally accessible resource\n- Submission state history and garbage collection\n\nSome suggested libraries:\n\n- [TanStack Query](https://tanstack.com/query/latest/docs/react/guides/mutations)\n- [SWR](https://swr.vercel.app/)\n- [RTK Query](https://redux-toolkit.js.org/rtk-query/overview)\n- [urql](https://formidable.com/open-source/urql/)\n- [Relay](https://relay.dev/)\n- [Apollo](https://www.apollographql.com/docs/react/)\n\nOr, even...\n\n- [Zustand](https://zustand-demo.pmnd.rs/)\n- [Jotai](https://jotai.org/)\n- [Recoil](https://recoiljs.org/)\n- [Redux](https://redux.js.org/)\n\nSimilar to data fetching, mutation state isn't a one-size-fits-all solution, so you'll need to pick a solution that fits your needs and your team's needs. We recommend trying out a few different solutions and seeing what works best for you.\n\n> \u26A0\uFE0F Still here? Submission state is an interesting topic when it comes to persistence. Do you keep every mutation around forever? How do you know when to get rid of it? What if the user navigates away from the screen and then back? Let's dig in!\n\n## Invalidating TanStack Router after a mutation\n\nTanStack Router comes with short-term caching built-in. So even though we're not storing any data after a route match is unmounted, there is a high probability that if any mutations are made related to the data stored in the Router, the current route matches' data could become stale.\n\nWhen mutations related to loader data are made, we can use `router.invalidate` to force the router to reload all of the current route matches:\n\n```tsx\nconst router = useRouter()\n\nconst addTodo = async (todo: Todo) => {\n try {\n await api.addTodo()\n router.invalidate()\n } catch {\n //\n }\n}\n```\n\nInvalidating all of the current route matches happens in the background, so existing data will continue to be served until the new data is ready, just as if you were navigating to a new route.\n\nIf you want to await the invalidation until all loaders have finished, pass `{sync: true}` into `router.invalidate`:\n\n```tsx\nconst router = useRouter()\n\nconst addTodo = async (todo: Todo) => {\n try {\n await api.addTodo()\n await router.invalidate({ sync: true })\n } catch {\n //\n }\n}\n```\n\n## Long-term mutation State\n\nRegardless of the mutation library used, mutations often create state related to their submission. While most mutations are set-and-forget, some mutation states are more long-lived, either to support optimistic UI or to provide feedback to the user about the status of their submissions. Most state managers will correctly keep this submission state around and expose it to make it possible to show UI elements like loading spinners, success messages, error messages, etc.\n\nLet's consider the following interactions:\n\n- User navigates to the `/posts/123/edit` screen to edit a post\n- User edits the `123` post and upon success, sees a success message below the editor that the post was updated\n- User navigates to the `/posts` screen\n- User navigates back to the `/posts/123/edit` screen again\n\nWithout notifying your mutation management library about the route change, it's possible that your submission state could still be around and your user would still see the **\"Post updated successfully\"** message when they return to the previous screen. This is not ideal. Obviously, our intent wasn't to keep this mutation state around forever, right?!\n\n## Using mutation keys\n\nHopefully and hypothetically, the easiest way is for your mutation library to support a keying mechanism that will allow your mutations's state to be reset when the key changes:\n\n```tsx\nconst routeApi = getRouteApi('/room/$roomId/chat')\n\nfunction ChatRoom() {\n const { roomId } = routeApi.useParams()\n\n const sendMessageMutation = useCoolMutation({\n fn: sendMessage,\n // Clear the mutation state when the roomId changes\n // including any submission state\n key: ['sendMessage', roomId],\n })\n\n // Fire off a bunch of messages\n const test = () => {\n sendMessageMutation.mutate({ roomId, message: 'Hello!' })\n sendMessageMutation.mutate({ roomId, message: 'How are you?' })\n sendMessageMutation.mutate({ roomId, message: 'Goodbye!' })\n }\n\n return (\n <>\n {sendMessageMutation.submissions.map((submission) => {\n return (\n
\n
{submission.status}
\n
{submission.message}
\n
\n )\n })}\n >\n )\n}\n```\n\n## Using the `router.subscribe` method\n\nSee the [Router Events guide](./router-events.md) for a more complete walkthrough of the available events and when to use them.\n\nFor libraries that don't have a keying mechanism, we'll likely need to manually reset the mutation state when the user navigates away from the screen. To solve this, we can use TanStack Router's `invalidate` and `subscribe` method to clear mutation states when the user is no longer in need of them.\n\nThe `router.subscribe` method is a function that subscribes a callback to various router events. The event in particular that we'll use here is the `onResolved` event. It's important to understand that this event is fired when the location path is _changed (not just reloaded) and has finally resolved_.\n\nThis is a great place to reset your old mutation states. Here's an example:\n\n```tsx\nconst router = createRouter()\nconst coolMutationCache = createCoolMutationCache()\n\nconst unsubscribeFn = router.subscribe('onResolved', () => {\n // Reset mutation states when the route changes\n coolMutationCache.clear()\n})\n```\n\n# Deferred Data Loading\n\nTanStack Router is designed to run loaders in parallel and wait for all of them to resolve before rendering the next route. This is great most of the time, but occasionally, you may want to show the user something sooner while the rest of the data loads in the background.\n\nDeferred data loading is a pattern that allows the router to render the next location's critical data/markup while slower, non-critical route data is resolved in the background. This process works on both the client and server (via streaming) and is a great way to improve the perceived performance of your application.\n\nIf you are using a library like [TanStack Query](https://tanstack.com/query/latest) or any other data fetching library, then deferred data loading works a bit differently. Skip ahead to the [Deferred Data Loading with External Libraries](#deferred-data-loading-with-external-libraries) section for more information.\n\n## Deferred Data Loading with `Await`\n\nTo defer slow or non-critical data, return an **unawaited/unresolved** promise anywhere in your loader response:\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute, defer } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/$postId')({\n loader: async () => {\n // Fetch some slower data, but do not await it\n const slowDataPromise = fetchSlowData()\n\n // Fetch and await some data that resolves quickly\n const fastData = await fetchFastData()\n\n return {\n fastData,\n deferredSlowData: slowDataPromise,\n }\n },\n})\n```\n\nAs soon as any awaited promises are resolved, the next route will begin rendering while the deferred promises continue to resolve.\n\nIn the component, deferred promises can be resolved and utilized using the `Await` component:\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute, Await } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/$postId')({\n // ...\n component: PostIdComponent,\n})\n\nfunction PostIdComponent() {\n const { deferredSlowData, fastData } = Route.useLoaderData()\n\n // do something with fastData\n\n return (\n Loading...}>\n {(data) => {\n return
{data}
\n }}\n \n )\n}\n```\n\n> [!TIP]\n> If your component is code-split, you can use the [getRouteApi function](./code-splitting.md#manually-accessing-route-apis-in-other-files-with-the-getrouteapi-helper) to avoid having to import the `Route` configuration to get access to the typed `useLoaderData()` hook.\n\nThe `Await` component resolves the promise by triggering the nearest suspense boundary until it is resolved, after which it renders the component's `children` as a function with the resolved data.\n\nIf the promise is rejected, the `Await` component will throw the serialized error, which can be caught by the nearest error boundary.\n\n\n\n# React\n\n> [!TIP]\n> In React 19, you can use the `use()` hook instead of `Await`\n\n\n\n## Deferred Data Loading with External libraries\n\nWhen your strategy for fetching information for the route relies on [External Data Loading](./external-data-loading.md) with an external library like [TanStack Query](https://tanstack.com/query), deferred data loading works a bit differently, as the library handles the data fetching and caching for you outside of TanStack Router.\n\nSo, instead of using `defer` and `Await`, you'll instead want to use the Route's `loader` to kick off the data fetching and then use the library's hooks to access the data in your components.\n\n\n\n# React\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute } from '@tanstack/react-router'\nimport { slowDataOptions, fastDataOptions } from '~/api/query-options'\n\nexport const Route = createFileRoute('/posts/$postId')({\n loader: async ({ context: { queryClient } }) => {\n // Kick off the fetching of some slower data, but do not await it\n queryClient.prefetchQuery(slowDataOptions())\n\n // Fetch and await some data that resolves quickly\n await queryClient.ensureQueryData(fastDataOptions())\n },\n})\n```\n\n# Solid\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute } from '@tanstack/solid-router'\nimport { slowDataOptions, fastDataOptions } from '~/api/query-options'\n\nexport const Route = createFileRoute('/posts/$postId')({\n loader: async ({ context: { queryClient } }) => {\n // Kick off the fetching of some slower data, but do not await it\n queryClient.prefetchQuery(slowDataOptions())\n\n // Fetch and await some data that resolves quickly\n await queryClient.ensureQueryData(fastDataOptions())\n },\n})\n```\n\n\n\nThen in your component, you can use the library's hooks to access the data:\n\n\n\n# React\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute } from '@tanstack/react-router'\nimport { useSuspenseQuery } from '@tanstack/react-query'\nimport { slowDataOptions, fastDataOptions } from '~/api/query-options'\n\nexport const Route = createFileRoute('/posts/$postId')({\n // ...\n component: PostIdComponent,\n})\n\nfunction PostIdComponent() {\n const fastData = useSuspenseQuery(fastDataOptions())\n\n // do something with fastData\n\n return (\n Loading...}>\n \n \n )\n}\n\nfunction SlowDataComponent() {\n const data = useSuspenseQuery(slowDataOptions())\n\n return
{data}
\n}\n```\n\n# Solid\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute } from '@tanstack/solid-router'\nimport { useSuspenseQuery } from '@tanstack/solid-query'\nimport { slowDataOptions, fastDataOptions } from '~/api/query-options'\n\nexport const Route = createFileRoute('/posts/$postId')({\n // ...\n component: PostIdComponent,\n})\n\nfunction PostIdComponent() {\n const fastData = useSuspenseQuery(fastDataOptions())\n\n // do something with fastData\n\n return (\n Loading...}>\n \n \n )\n}\n\nfunction SlowDataComponent() {\n const data = useSuspenseQuery(slowDataOptions())\n\n return
{data()}
\n}\n```\n\n\n\n## Caching and Invalidation\n\nStreamed promises follow the same lifecycle as the loader data they are associated with. They can even be preloaded!\n\n\n\n# React\n\n## SSR & Streaming Deferred Data\n\n**Streaming requires a server that supports it and for TanStack Router to be configured to use it properly.**\n\nPlease read the entire [Streaming SSR Guide](./ssr.md#streaming-ssr) for step by step instructions on how to set up your server for streaming.\n\n## SSR Streaming Lifecycle\n\nThe following is a high-level overview of how deferred data streaming works with TanStack Router:\n\n- Server\n - Promises are marked and tracked as they are returned from route loaders\n - All loaders resolve and any deferred promises are serialized and embedded into the html\n - The route begins to render\n - Deferred promises rendered with the `` component trigger suspense boundaries, allowing the server to stream html up to that point\n- Client\n - The client receives the initial html from the server\n - `` components suspend with placeholder promises while they wait for their data to resolve on the server\n- Server\n - As deferred promises resolve, their results (or errors) are serialized and streamed to the client via an inline script tag\n - The resolved `` components and their suspense boundaries are resolved and their resulting HTML is streamed to the client along with their dehydrated data\n- Client\n - The suspended placeholder promises within `` are resolved with the streamed data/error responses and either render the result or throw the error to the nearest error boundary\n\n\n\n# Document Head Management\n\nDocument head management is the process of managing the head, title, meta, link, and script tags of a document and TanStack Router provides a robust way to manage the document head for full-stack applications that use Start and for single-page applications that use TanStack Router. It provides:\n\n- Automatic deduping of `title` and `meta` tags\n- Automatic loading/unloading of tags based on route visibility\n- A composable way to merge `title` and `meta` tags from nested routes\n\nFor full-stack applications that use Start, and even for single-page applications that use TanStack Router, managing the document head is a crucial part of any application for the following reasons:\n\n- SEO\n- Social media sharing\n- Analytics\n- CSS and JS loading/unloading\n\nTo manage the document head, it's required that you render both the `` and `` components and use the `routeOptions.head` property to manage the head of a route, which returns an object with `title`, `meta`, `links`, `styles`, and `scripts` properties.\n\n## Managing the Document Head\n\n```tsx\nexport const Route = createRootRoute({\n head: () => ({\n meta: [\n {\n name: 'description',\n content: 'My App is a web application',\n },\n {\n title: 'My App',\n },\n ],\n links: [\n {\n rel: 'icon',\n href: '/favicon.ico',\n },\n ],\n styles: [\n {\n media: 'all and (max-width: 500px)',\n children: `p {\n color: blue;\n background-color: yellow;\n }`,\n },\n ],\n scripts: [\n {\n src: 'https://www.google-analytics.com/analytics.js',\n },\n ],\n }),\n})\n```\n\n### Deduping\n\nOut of the box, TanStack Router will dedupe `title` and `meta` tags, preferring the **last** occurrence of each tag found in nested routes.\n\n- `title` tags defined in nested routes will override a `title` tag defined in a parent route (but you can compose them together, which is covered in a future section of this guide)\n- `meta` tags with the same `name` or `property` will be overridden by the last occurrence of that tag found in nested routes\n\n### ``\n\nThe `` component is **required** to render the head, title, meta, link, and head-related script tags of a document.\n\nIt should be **rendered either in the `` tag of your root layout or as high up in the component tree as possible** if your application doesn't or can't manage the `` tag.\n\nFor manifest-managed assets, you can also set `crossorigin` values on emitted\n`modulepreload` and stylesheet links:\n\n```tsx\n\n\n\n```\n\n`assetCrossOrigin` only applies to manifest-managed asset links emitted by Start.\nIf you also set `crossOrigin` via `transformAssets` (either the object shorthand\nor a callback return value), `assetCrossOrigin` wins.\n\n### Start/Full-Stack Applications\n\n\n\n# React\n\n```tsx\nimport { HeadContent } from '@tanstack/react-router'\n\nexport const Route = createRootRoute({\n component: () => (\n \n \n \n \n \n \n \n \n ),\n})\n```\n\n# Solid\n\n```tsx\nimport { HeadContent } from '@tanstack/solid-router'\n\nexport const Route = createRootRoute({\n component: () => (\n \n \n \n \n \n \n \n \n ),\n})\n```\n\n\n\n### Single-Page Applications\n\nFirst, remove the `` tag from the index.html if you have set any.\n\n\n\n# React\n\n```tsx\nimport { HeadContent } from '@tanstack/react-router'\n\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n \n \n >\n ),\n})\n```\n\n# Solid\n\n```tsx\nimport { HeadContent } from '@tanstack/solid-router'\n\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n \n \n >\n ),\n})\n```\n\n\n\n## Managing Body Scripts\n\nIn addition to scripts that can be rendered in the `` tag, you can also render scripts in the `` tag using the `routeOptions.scripts` property. This is useful for loading scripts (even inline scripts) that require the DOM to be loaded, but before the main entry point of your application (which includes hydration if you're using Start or a full-stack implementation of TanStack Router).\n\nTo do this, you must:\n\n- Use the `scripts` property of the `routeOptions` object\n- [Render the `` component](#scripts)\n\n```tsx\nexport const Route = createRootRoute({\n scripts: () => [\n {\n children: 'console.log(\"Hello, world!\")',\n },\n ],\n})\n```\n\n### ``\n\nThe `` component is **required** to render the body scripts of a document. It should be rendered either in the `` tag of your root layout or as high up in the component tree as possible if your application doesn't or can't manage the `` tag.\n\n### Example\n\n\n\n# React\n\n```tsx\nimport { createRootRoute, Scripts } from '@tanstack/react-router'\nexport const Route = createFileRoute('/')({\n component: () => (\n \n \n \n \n \n \n \n ),\n})\n```\n\n# Solid\n\n```tsx\nimport { createFileRoute, Scripts } from '@tanstack/solid-router'\nexport const Route = createRootRoute('/')({\n component: () => (\n \n \n \n \n \n \n \n ),\n})\n```\n\n\n\n## Inline Scripts with ScriptOnce\n\nFor scripts that must run before React hydrates (like theme detection), use `ScriptOnce`. This is particularly useful for avoiding flash of unstyled content (FOUC) or theme flicker.\n\n\n\n# React\n\n```tsx\nimport { ScriptOnce } from '@tanstack/react-router'\n\nconst themeScript = `(function() {\n try {\n const theme = localStorage.getItem('theme') || 'auto';\n const resolved = theme === 'auto'\n ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')\n : theme;\n document.documentElement.classList.add(resolved);\n } catch (e) {}\n})();`\n\nfunction ThemeProvider({ children }) {\n return (\n <>\n \n {children}\n >\n )\n}\n```\n\n# Solid\n\n```tsx\nimport { ScriptOnce } from '@tanstack/solid-router'\n\nconst themeScript = `(function() {\n try {\n const theme = localStorage.getItem('theme') || 'auto';\n const resolved = theme === 'auto'\n ? (matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')\n : theme;\n document.documentElement.classList.add(resolved);\n } catch (e) {}\n})();`\n\nfunction ThemeProvider({ children }) {\n return (\n <>\n \n {children}\n >\n )\n}\n```\n\n\n\n### How ScriptOnce Works\n\n1. During SSR, renders a `