@tanstack/react-router 1.133.27 → 1.133.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/cjs/ClientOnly.cjs.map +1 -1
  2. package/dist/cjs/ClientOnly.d.cts +5 -0
  3. package/dist/cjs/HeadContent.cjs.map +1 -1
  4. package/dist/cjs/HeadContent.d.cts +9 -0
  5. package/dist/cjs/Matches.cjs.map +1 -1
  6. package/dist/cjs/Matches.d.cts +12 -0
  7. package/dist/cjs/RouterProvider.cjs.map +1 -1
  8. package/dist/cjs/RouterProvider.d.cts +9 -0
  9. package/dist/cjs/ScriptOnce.cjs.map +1 -1
  10. package/dist/cjs/ScriptOnce.d.cts +4 -0
  11. package/dist/cjs/Scripts.cjs.map +1 -1
  12. package/dist/cjs/Scripts.d.cts +4 -0
  13. package/dist/cjs/awaited.cjs.map +1 -1
  14. package/dist/cjs/awaited.d.cts +5 -0
  15. package/dist/cjs/fileRoute.cjs.map +1 -1
  16. package/dist/cjs/fileRoute.d.cts +23 -0
  17. package/dist/cjs/link.cjs +1 -1
  18. package/dist/cjs/link.cjs.map +1 -1
  19. package/dist/cjs/link.d.cts +14 -0
  20. package/dist/cjs/router.cjs.map +1 -1
  21. package/dist/cjs/router.d.cts +5 -0
  22. package/dist/cjs/useLoaderData.cjs.map +1 -1
  23. package/dist/cjs/useLoaderData.d.cts +4 -0
  24. package/dist/cjs/useLoaderDeps.cjs.map +1 -1
  25. package/dist/cjs/useLoaderDeps.d.cts +4 -0
  26. package/dist/cjs/useLocation.cjs.map +1 -1
  27. package/dist/cjs/useLocation.d.cts +5 -0
  28. package/dist/cjs/useMatch.cjs.map +1 -1
  29. package/dist/cjs/useMatch.d.cts +0 -8
  30. package/dist/cjs/useParams.cjs.map +1 -1
  31. package/dist/cjs/useParams.d.cts +4 -0
  32. package/dist/cjs/useRouter.cjs.map +1 -1
  33. package/dist/cjs/useRouter.d.cts +5 -0
  34. package/dist/cjs/useRouterState.cjs.map +1 -1
  35. package/dist/cjs/useRouterState.d.cts +5 -0
  36. package/dist/cjs/useSearch.cjs.map +1 -1
  37. package/dist/cjs/useSearch.d.cts +4 -0
  38. package/dist/esm/ClientOnly.d.ts +5 -0
  39. package/dist/esm/ClientOnly.js.map +1 -1
  40. package/dist/esm/HeadContent.d.ts +9 -0
  41. package/dist/esm/HeadContent.js.map +1 -1
  42. package/dist/esm/Matches.d.ts +12 -0
  43. package/dist/esm/Matches.js.map +1 -1
  44. package/dist/esm/RouterProvider.d.ts +9 -0
  45. package/dist/esm/RouterProvider.js.map +1 -1
  46. package/dist/esm/ScriptOnce.d.ts +4 -0
  47. package/dist/esm/ScriptOnce.js.map +1 -1
  48. package/dist/esm/Scripts.d.ts +4 -0
  49. package/dist/esm/Scripts.js.map +1 -1
  50. package/dist/esm/awaited.d.ts +5 -0
  51. package/dist/esm/awaited.js.map +1 -1
  52. package/dist/esm/fileRoute.d.ts +23 -0
  53. package/dist/esm/fileRoute.js.map +1 -1
  54. package/dist/esm/link.d.ts +14 -0
  55. package/dist/esm/link.js +1 -1
  56. package/dist/esm/link.js.map +1 -1
  57. package/dist/esm/router.d.ts +5 -0
  58. package/dist/esm/router.js.map +1 -1
  59. package/dist/esm/useLoaderData.d.ts +4 -0
  60. package/dist/esm/useLoaderData.js.map +1 -1
  61. package/dist/esm/useLoaderDeps.d.ts +4 -0
  62. package/dist/esm/useLoaderDeps.js.map +1 -1
  63. package/dist/esm/useLocation.d.ts +5 -0
  64. package/dist/esm/useLocation.js.map +1 -1
  65. package/dist/esm/useMatch.d.ts +0 -8
  66. package/dist/esm/useMatch.js.map +1 -1
  67. package/dist/esm/useParams.d.ts +4 -0
  68. package/dist/esm/useParams.js.map +1 -1
  69. package/dist/esm/useRouter.d.ts +5 -0
  70. package/dist/esm/useRouter.js.map +1 -1
  71. package/dist/esm/useRouterState.d.ts +5 -0
  72. package/dist/esm/useRouterState.js.map +1 -1
  73. package/dist/esm/useSearch.d.ts +4 -0
  74. package/dist/esm/useSearch.js.map +1 -1
  75. package/dist/llms/rules/installation.d.ts +1 -1
  76. package/dist/llms/rules/installation.js +1 -1
  77. package/dist/llms/rules/setup-and-architecture.d.ts +1 -1
  78. package/dist/llms/rules/setup-and-architecture.js +7 -7
  79. package/package.json +3 -3
  80. package/src/ClientOnly.tsx +8 -0
  81. package/src/HeadContent.tsx +9 -0
  82. package/src/Matches.tsx +12 -0
  83. package/src/RouterProvider.tsx +9 -0
  84. package/src/ScriptOnce.tsx +4 -0
  85. package/src/Scripts.tsx +4 -0
  86. package/src/awaited.tsx +5 -0
  87. package/src/fileRoute.ts +23 -0
  88. package/src/link.tsx +18 -1
  89. package/src/router.ts +5 -0
  90. package/src/useLoaderData.tsx +4 -0
  91. package/src/useLoaderDeps.tsx +4 -0
  92. package/src/useLocation.tsx +5 -0
  93. package/src/useMatch.tsx +0 -8
  94. package/src/useParams.tsx +4 -0
  95. package/src/useRouter.tsx +5 -0
  96. package/src/useRouterState.tsx +5 -0
  97. package/src/useSearch.tsx +4 -0
@@ -18,4 +18,8 @@ export type UseSearchRoute<out TFrom> = <TRouter extends AnyRouter = RegisteredR
18
18
  * @returns The search object (or selected value) for the matched route.
19
19
  * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useSearchHook
20
20
  */
21
+ /**
22
+ * Read and select the current route's search parameters with type-safety.
23
+ * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useSearchHook
24
+ */
21
25
  export declare function useSearch<TRouter extends AnyRouter = RegisteredRouter, const TFrom extends string | undefined = undefined, TStrict extends boolean = true, TThrow extends boolean = true, TSelected = unknown, TStructuralSharing extends boolean = boolean>(opts: UseSearchOptions<TRouter, TFrom, TStrict, ThrowConstraint<TStrict, TThrow>, TSelected, TStructuralSharing>): ThrowOrOptional<UseSearchResult<TRouter, TFrom, TStrict, TSelected>, TThrow>;
@@ -1 +1 @@
1
- {"version":3,"file":"useSearch.js","sources":["../../src/useSearch.tsx"],"sourcesContent":["import { useMatch } from './useMatch'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRouter,\n RegisteredRouter,\n ResolveUseSearch,\n StrictOrFrom,\n ThrowConstraint,\n ThrowOrOptional,\n UseSearchResult,\n} from '@tanstack/router-core'\n\nexport interface UseSearchBaseOptions<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean,\n TThrow extends boolean,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n state: ResolveUseSearch<TRouter, TFrom, TStrict>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n shouldThrow?: TThrow\n}\n\nexport type UseSearchOptions<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean,\n TThrow extends boolean,\n TSelected,\n TStructuralSharing,\n> = StrictOrFrom<TRouter, TFrom, TStrict> &\n UseSearchBaseOptions<\n TRouter,\n TFrom,\n TStrict,\n TThrow,\n TSelected,\n TStructuralSharing\n > &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>\n\nexport type UseSearchRoute<out TFrom> = <\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseSearchBaseOptions<\n TRouter,\n TFrom,\n /* TStrict */ true,\n /* TThrow */ true,\n TSelected,\n TStructuralSharing\n > &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n) => UseSearchResult<TRouter, TFrom, true, TSelected>\n\n/**\n * Read and select the current route's search parameters with type-safety.\n *\n * Options:\n * - `from`/`strict`: Control which route's search is read and how strictly it's typed\n * - `select`: Map the search object to a derived value for render optimization\n * - `structuralSharing`: Enable structural sharing for stable references\n * - `shouldThrow`: Throw when the route is not found (strict contexts)\n *\n * @returns The search object (or selected value) for the matched route.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useSearchHook\n */\nexport function useSearch<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string | undefined = undefined,\n TStrict extends boolean = true,\n TThrow extends boolean = true,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts: UseSearchOptions<\n TRouter,\n TFrom,\n TStrict,\n ThrowConstraint<TStrict, TThrow>,\n TSelected,\n TStructuralSharing\n >,\n): ThrowOrOptional<\n UseSearchResult<TRouter, TFrom, TStrict, TSelected>,\n TThrow\n> {\n return useMatch({\n from: opts.from!,\n strict: opts.strict,\n shouldThrow: opts.shouldThrow,\n structuralSharing: opts.structuralSharing,\n select: (match: any) => {\n return opts.select ? opts.select(match.search) : match.search\n },\n }) as any\n}\n"],"names":[],"mappings":";AA2EO,SAAS,UAQd,MAWA;AACA,SAAO,SAAS;AAAA,IACd,MAAM,KAAK;AAAA,IACX,QAAQ,KAAK;AAAA,IACb,aAAa,KAAK;AAAA,IAClB,mBAAmB,KAAK;AAAA,IACxB,QAAQ,CAAC,UAAe;AACtB,aAAO,KAAK,SAAS,KAAK,OAAO,MAAM,MAAM,IAAI,MAAM;AAAA,IACzD;AAAA,EAAA,CACD;AACH;"}
1
+ {"version":3,"file":"useSearch.js","sources":["../../src/useSearch.tsx"],"sourcesContent":["import { useMatch } from './useMatch'\nimport type {\n StructuralSharingOption,\n ValidateSelected,\n} from './structuralSharing'\nimport type {\n AnyRouter,\n RegisteredRouter,\n ResolveUseSearch,\n StrictOrFrom,\n ThrowConstraint,\n ThrowOrOptional,\n UseSearchResult,\n} from '@tanstack/router-core'\n\nexport interface UseSearchBaseOptions<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean,\n TThrow extends boolean,\n TSelected,\n TStructuralSharing,\n> {\n select?: (\n state: ResolveUseSearch<TRouter, TFrom, TStrict>,\n ) => ValidateSelected<TRouter, TSelected, TStructuralSharing>\n shouldThrow?: TThrow\n}\n\nexport type UseSearchOptions<\n TRouter extends AnyRouter,\n TFrom,\n TStrict extends boolean,\n TThrow extends boolean,\n TSelected,\n TStructuralSharing,\n> = StrictOrFrom<TRouter, TFrom, TStrict> &\n UseSearchBaseOptions<\n TRouter,\n TFrom,\n TStrict,\n TThrow,\n TSelected,\n TStructuralSharing\n > &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>\n\nexport type UseSearchRoute<out TFrom> = <\n TRouter extends AnyRouter = RegisteredRouter,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts?: UseSearchBaseOptions<\n TRouter,\n TFrom,\n /* TStrict */ true,\n /* TThrow */ true,\n TSelected,\n TStructuralSharing\n > &\n StructuralSharingOption<TRouter, TSelected, TStructuralSharing>,\n) => UseSearchResult<TRouter, TFrom, true, TSelected>\n\n/**\n * Read and select the current route's search parameters with type-safety.\n *\n * Options:\n * - `from`/`strict`: Control which route's search is read and how strictly it's typed\n * - `select`: Map the search object to a derived value for render optimization\n * - `structuralSharing`: Enable structural sharing for stable references\n * - `shouldThrow`: Throw when the route is not found (strict contexts)\n *\n * @returns The search object (or selected value) for the matched route.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useSearchHook\n */\n/**\n * Read and select the current route's search parameters with type-safety.\n * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useSearchHook\n */\nexport function useSearch<\n TRouter extends AnyRouter = RegisteredRouter,\n const TFrom extends string | undefined = undefined,\n TStrict extends boolean = true,\n TThrow extends boolean = true,\n TSelected = unknown,\n TStructuralSharing extends boolean = boolean,\n>(\n opts: UseSearchOptions<\n TRouter,\n TFrom,\n TStrict,\n ThrowConstraint<TStrict, TThrow>,\n TSelected,\n TStructuralSharing\n >,\n): ThrowOrOptional<\n UseSearchResult<TRouter, TFrom, TStrict, TSelected>,\n TThrow\n> {\n return useMatch({\n from: opts.from!,\n strict: opts.strict,\n shouldThrow: opts.shouldThrow,\n structuralSharing: opts.structuralSharing,\n select: (match: any) => {\n return opts.select ? opts.select(match.search) : match.search\n },\n }) as any\n}\n"],"names":[],"mappings":";AA+EO,SAAS,UAQd,MAWA;AACA,SAAO,SAAS;AAAA,IACd,MAAM,KAAK;AAAA,IACX,QAAQ,KAAK;AAAA,IACb,aAAa,KAAK;AAAA,IAClB,mBAAmB,KAAK;AAAA,IACxB,QAAQ,CAAC,UAAe;AACtB,aAAO,KAAK,SAAS,KAAK,OAAO,MAAM,MAAM,IAAI,MAAM;AAAA,IACzD;AAAA,EAAA,CACD;AACH;"}
@@ -1,2 +1,2 @@
1
- declare const _default: "# Manual Setup\n\nTo set up TanStack Router manually in a React project, follow the steps below. This gives you a bare minimum setup to get going with TanStack Router using both file-based route generation and code-based route configuration:\n\n## Using File-Based Route Generation\n\n#### Install TanStack Router, Vite Plugin, and the Router Devtools\n\n```sh\nnpm install @tanstack/react-router @tanstack/react-router-devtools\nnpm install -D @tanstack/router-plugin\n# or\npnpm add @tanstack/react-router @tanstack/react-router-devtools\npnpm add -D @tanstack/router-plugin\n# or\nyarn add @tanstack/react-router @tanstack/react-router-devtools\nyarn add -D @tanstack/router-plugin\n# or\nbun add @tanstack/react-router @tanstack/react-router-devtools\nbun add -D @tanstack/router-plugin\n# or\ndeno add npm:@tanstack/react-router npm:@tanstack/router-plugin npm:@tanstack/react-router-devtools\n```\n\n#### Configure the Vite Plugin\n\n```tsx\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n react(),\n // ...,\n ],\n})\n```\n\n> [!TIP]\n> If you are not using Vite, or any of the supported bundlers, you can check out the [TanStack Router CLI](../with-router-cli) guide for more info.\n\nCreate the following files:\n\n- `src/routes/__root.tsx` (with two '`_`' characters)\n- `src/routes/index.tsx`\n- `src/routes/about.tsx`\n- `src/main.tsx`\n\n#### `src/routes/__root.tsx`\n\n```tsx\nimport { createRootRoute, Link, Outlet } from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nconst RootLayout = () => (\n <>\n <div className=\"p-2 flex gap-2\">\n <Link to=\"/\" className=\"[&.active]:font-bold\">\n Home\n </Link>{' '}\n <Link to=\"/about\" className=\"[&.active]:font-bold\">\n About\n </Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n)\n\nexport const Route = createRootRoute({ component: RootLayout })\n```\n\n#### `src/routes/index.tsx`\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: Index,\n})\n\nfunction Index() {\n return (\n <div className=\"p-2\">\n <h3>Welcome Home!</h3>\n </div>\n )\n}\n```\n\n#### `src/routes/about.tsx`\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/about')({\n component: About,\n})\n\nfunction About() {\n return <div className=\"p-2\">Hello from About!</div>\n}\n```\n\n#### `src/main.tsx`\n\nRegardless of whether you are using the `@tanstack/router-plugin` package and running the `npm run dev`/`npm run build` scripts, or manually running the `tsr watch`/`tsr generate` commands from your package scripts, the route tree file will be generated at `src/routeTree.gen.ts`.\n\nImport the generated route tree and create a new router instance:\n\n```tsx\nimport { StrictMode } from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { RouterProvider, createRouter } from '@tanstack/react-router'\n\n// Import the generated route tree\nimport { routeTree } from './routeTree.gen'\n\n// Create a new router instance\nconst router = createRouter({ routeTree })\n\n// Register the router instance for type safety\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\n// Render the app\nconst rootElement = document.getElementById('root')!\nif (!rootElement.innerHTML) {\n const root = ReactDOM.createRoot(rootElement)\n root.render(\n <StrictMode>\n <RouterProvider router={router} />\n </StrictMode>,\n )\n}\n```\n\nIf you are working with this pattern you should change the `id` of the root `<div>` on your `index.html` file to `<div id='root'></div>`\n\n## Using Code-Based Route Configuration\n\n> [!IMPORTANT]\n> The following example shows how to configure routes using code, and for simplicity's sake is in a single file for this demo. While code-based generation allows you to declare many routes and even the router instance in a single file, we recommend splitting your routes into separate files for better organization and performance as your application grows.\n\n```tsx\nimport { StrictMode } from 'react'\nimport ReactDOM from 'react-dom/client'\nimport {\n Outlet,\n RouterProvider,\n Link,\n createRouter,\n createRoute,\n createRootRoute,\n} from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <div className=\"p-2 flex gap-2\">\n <Link to=\"/\" className=\"[&.active]:font-bold\">\n Home\n </Link>{' '}\n <Link to=\"/about\" className=\"[&.active]:font-bold\">\n About\n </Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst indexRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n component: function Index() {\n return (\n <div className=\"p-2\">\n <h3>Welcome Home!</h3>\n </div>\n )\n },\n})\n\nconst aboutRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/about',\n component: function About() {\n return <div className=\"p-2\">Hello from About!</div>\n },\n})\n\nconst routeTree = rootRoute.addChildren([indexRoute, aboutRoute])\n\nconst router = createRouter({ routeTree })\n\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\nconst rootElement = document.getElementById('app')!\nif (!rootElement.innerHTML) {\n const root = ReactDOM.createRoot(rootElement)\n root.render(\n <StrictMode>\n <RouterProvider router={router} />\n </StrictMode>,\n )\n}\n```\n\nIf you glossed over these examples or didn't understand something, we don't blame you, because there's so much more to learn to really take advantage of TanStack Router! Let's move on.\n\n# Migration from React Location\n\nBefore you begin your journey in migrating from React Location, it's important that you have a good understanding of the [Routing Concepts](../routing/routing-concepts.md) and [Design Decisions](../decisions-on-dx.md) used by TanStack Router.\n\n## Differences between React Location and TanStack Router\n\nReact Location and TanStack Router share much of same design decisions concepts, but there are some key differences that you should be aware of.\n\n- React Location uses _generics_ to infer types for routes, while TanStack Router uses _module declaration merging_ to infer types.\n- Route configuration in React Location is done using a single array of route definitions, while in TanStack Router, route configuration is done using a tree of route definitions starting with the [root route](../routing/routing-concepts.md#the-root-route).\n- [File-based routing](../routing/file-based-routing.md) is the recommended way to define routes in TanStack Router, while React Location only allows you to define routes in a single file using a code-based approach.\n - TanStack Router does support a [code-based approach](../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../decisions-on-dx.md#3-why-is-file-based-routing-the-preferred-way-to-define-routes)\n\n## Migration guide\n\nIn this guide we'll go over the process of migrating the [React Location Basic example](https://github.com/TanStack/router/tree/react-location/examples/basic) over to TanStack Router using file-based routing, with the end goal of having the same functionality as the original example (styling and other non-routing related code will be omitted).\n\n> [!TIP]\n> To use a code-based approach for defining your routes, you can read the [code-based Routing](../routing/code-based-routing.md) guide.\n\n### Step 1: Swap over to TanStack Router's dependencies\n\nFirst, we need to install the dependencies for TanStack Router. For detailed installation instructions, see our [How to Install TanStack Router](../how-to/install.md) guide.\n\n```sh\nnpm install @tanstack/react-router @tanstack/router-devtools\n```\n\nAnd remove the React Location dependencies.\n\n```sh\nnpm uninstall @tanstack/react-location @tanstack/react-location-devtools\n```\n\n### Step 2: Use the file-based routing watcher\n\nIf your project uses Vite (or one of the supported bundlers), you can use the TanStack Router plugin to watch for changes in your routes files and automatically update the routes configuration.\n\nInstallation of the Vite plugin:\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nAnd add it to your `vite.config.js`:\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n // ...\n plugins: [tanstackRouter(), react()],\n})\n```\n\nHowever, if your application does not use Vite, you use one of our other [supported bundlers](../routing/file-based-routing.md#getting-started-with-file-based-routing), or you can use the `@tanstack/router-cli` package to watch for changes in your routes files and automatically update the routes configuration.\n\n### Step 3: Add the file-based configuration file to your project\n\nCreate a `tsr.config.json` file in the root of your project with the following content:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\"\n}\n```\n\nYou can find the full list of options for the `tsr.config.json` file [here](../../../api/file-based-routing.md).\n\n### Step 4: Create the routes directory\n\nCreate a `routes` directory in the `src` directory of your project.\n\n```sh\nmkdir src/routes\n```\n\n### Step 5: Create the root route file\n\n```tsx\n// src/routes/__root.tsx\nimport { createRootRoute, Outlet, Link } from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/router-devtools'\n\nexport const Route = createRootRoute({\n component: () => {\n return (\n <>\n <div>\n <Link to=\"/\" activeOptions={{ exact: true }}>\n Home\n </Link>\n <Link to=\"/posts\">Posts</Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n )\n },\n})\n```\n\n### Step 6: Create the index route file\n\n```tsx\n// src/routes/index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: Index,\n})\n```\n\n> You will need to move any related components and logic needed for the index route from the `src/index.tsx` file to the `src/routes/index.tsx` file.\n\n### Step 7: Create the posts route file\n\n```tsx\n// src/routes/posts.tsx\nimport { createFileRoute, Link, Outlet } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts')({\n component: Posts,\n loader: async () => {\n const posts = await fetchPosts()\n return {\n posts,\n }\n },\n})\n\nfunction Posts() {\n const { posts } = Route.useLoaderData()\n return (\n <div>\n <nav>\n {posts.map((post) => (\n <Link\n key={post.id}\n to={`/posts/$postId`}\n params={{ postId: post.id }}\n >\n {post.title}\n </Link>\n ))}\n </nav>\n <Outlet />\n </div>\n )\n}\n```\n\n> You will need to move any related components and logic needed for the posts route from the `src/index.tsx` file to the `src/routes/posts.tsx` file.\n\n### Step 8: Create the posts index route file\n\n```tsx\n// src/routes/posts.index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/')({\n component: PostsIndex,\n})\n```\n\n> You will need to move any related components and logic needed for the posts index route from the `src/index.tsx` file to the `src/routes/posts.index.tsx` file.\n\n### Step 9: Create the posts id route file\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/$postId')({\n component: PostsId,\n loader: async ({ params: { postId } }) => {\n const post = await fetchPost(postId)\n return {\n post,\n }\n },\n})\n\nfunction PostsId() {\n const { post } = Route.useLoaderData()\n // ...\n}\n```\n\n> You will need to move any related components and logic needed for the posts id route from the `src/index.tsx` file to the `src/routes/posts.$postId.tsx` file.\n\n### Step 10: Generate the route tree\n\nIf you are using one of the supported bundlers, the route tree will be generated automatically when you run the dev script.\n\nIf you are not using one of the supported bundlers, you can generate the route tree by running the following command:\n\n```sh\nnpx tsr generate\n```\n\n### Step 11: Update the main entry file to render the Router\n\nOnce you've generated the route-tree, you can then update the `src/index.tsx` file to create the router instance and render it.\n\n```tsx\n// src/index.tsx\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport { createRouter, RouterProvider } from '@tanstack/react-router'\n\n// Import the generated route tree\nimport { routeTree } from './routeTree.gen'\n\n// Create a new router instance\nconst router = createRouter({ routeTree })\n\n// Register the router instance for type safety\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\nconst domElementId = 'root' // Assuming you have a root element with the id 'root'\n\n// Render the app\nconst rootElement = document.getElementById(domElementId)\nif (!rootElement) {\n throw new Error(`Element with id ${domElementId} not found`)\n}\n\nReactDOM.createRoot(rootElement).render(\n <React.StrictMode>\n <RouterProvider router={router} />\n </React.StrictMode>,\n)\n```\n\n### Finished!\n\nYou should now have successfully migrated your application from React Location to TanStack Router using file-based routing.\n\nReact Location also has a few more features that you might be using in your application. Here are some guides to help you migrate those features:\n\n- [Search params](../guide/search-params.md)\n- [Data loading](../guide/data-loading.md)\n- [History types](../guide/history-types.md)\n- [Wildcard / Splat / Catch-all routes](../routing/routing-concepts.md#splat--catch-all-routes)\n- [Authenticated routes](../guide/authenticated-routes.md)\n\nTanStack Router also has a few more features that you might want to explore:\n\n- [Router Context](../guide/router-context.md)\n- [Preloading](../guide/preloading.md)\n- [Pathless Layout Routes](../routing/routing-concepts.md#pathless-layout-routes)\n- [Route masking](../guide/route-masking.md)\n- [SSR](../guide/ssr.md)\n- ... and more!\n\nIf you are facing any issues or have any questions, feel free to ask for help in the TanStack Discord.\n\n# Migration from React Router Checklist\n\n**_If your UI is blank, open the console, and you will probably have some errors that read something along the lines of `cannot use 'useNavigate' outside of context` . This means there are React Router api\u2019s that are still imported and referenced that you need to find and remove. The easiest way to make sure you find all React Router imports is to uninstall `react-router-dom` and then you should get typescript errors in your files. Then you will know what to change to a `@tanstack/react-router` import._**\n\nHere is the [example repo](https://github.com/Benanna2019/SickFitsForEveryone/tree/migrate-to-tanstack/router/React-Router)\n\n- [ ] Install Router - `npm i @tanstack/react-router` (see [detailed installation guide](../how-to/install.md))\n- [ ] **Optional:** Uninstall React Router to get TypeScript errors on imports.\n - At this point I don\u2019t know if you can do a gradual migration, but it seems likely you could have multiple router providers, not desirable.\n - The api\u2019s between React Router and TanStack Router are very similar and could most likely be handled in a sprint cycle or two if that is your companies way of doing things.\n- [ ] Create Routes for each existing React Router route we have\n- [ ] Create root route\n- [ ] Create router instance\n- [ ] Add global module in main.tsx\n- [ ] Remove any React Router (`createBrowserRouter` or `BrowserRouter`), `Routes`, and `Route` Components from main.tsx\n- [ ] **Optional:** Refactor `render` function for custom setup/providers - The repo referenced above has an example - This was necessary in the case of Supertokens. Supertoken has a specific setup with React Router and a different setup with all other React implementations\n- [ ] Set RouterProvider and pass it the router as the prop\n- [ ] Replace all instances of React Router `Link` component with `@tanstack/react-router` `Link` component\n - [ ] Add `to` prop with literal path\n - [ ] Add `params` prop, where necessary with params like so `params={{ orderId: order.id }}`\n- [ ] Replace all instances of React Router `useNavigate` hook with `@tanstack/react-router` `useNavigate` hook\n - [ ] Set `to` property and `params` property where needed\n- [ ] Replace any React Router `Outlet`'s with the `@tanstack/react-router` equivalent\n- [ ] If you are using `useSearchParams` hook from React Router, move the search params default value to the validateSearch property on a Route definition.\n - [ ] Instead of using the `useSearchParams` hook, use `@tanstack/react-router` `Link`'s search property to update the search params state\n - [ ] To read search params you can do something like the following\n - `const { page } = useSearch({ from: productPage.fullPath })`\n- [ ] If using React Router\u2019s `useParams` hook, update the import to be from `@tanstack/react-router` and set the `from` property to the literal path name where you want to read the params object from\n - So say we have a route with the path name `orders/$orderid`.\n - In the `useParams` hook we would set up our hook like so: `const params = useParams({ from: \"/orders/$orderId\" })`\n - Then wherever we wanted to access the order id we would get it off of the params object `params.orderId`\n\n# Installation with Esbuild\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Esbuild**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your configuration.\n\n```tsx\n// esbuild.config.js\nimport { tanstackRouter } from '@tanstack/router-plugin/esbuild'\n\nexport default {\n // ...\n plugins: [\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n ],\n}\n```\n\nOr, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-esbuild-file-based) and get started.\n\nNow that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Esbuild for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Router CLI\n\n> [!WARNING]\n> You should only use the TanStack Router CLI if you are not using a supported bundler. The CLI only supports the generation of the route tree file and does not provide any other features.\n\nTo use file-based routing with the TanStack Router CLI, you'll need to install the `@tanstack/router-cli` package.\n\n```sh\nnpm install -D @tanstack/router-cli\n```\n\nOnce installed, you'll need to amend your scripts in your `package.json` for the CLI to `watch` and `generate` files.\n\n```json\n{\n \"scripts\": {\n \"generate-routes\": \"tsr generate\",\n \"watch-routes\": \"tsr watch\",\n \"build\": \"npm run generate-routes && ...\",\n \"dev\": \"npm run watch-routes && ...\"\n }\n}\n```\n\n[//]: # 'AfterScripts'\n[//]: # 'AfterScripts'\n\nYou shouldn't forget to _ignore_ the generated route tree file. Head over to the [Ignoring the generated route tree file](#ignoring-the-generated-route-tree-file) section to learn more.\n\nWith the CLI installed, the following commands are made available via the `tsr` command\n\n## Using the `generate` command\n\nGenerates the routes for a project based on the provided configuration.\n\n```sh\ntsr generate\n```\n\n## Using the `watch` command\n\nContinuously watches the specified directories and regenerates routes as needed.\n\n**Usage:**\n\n```sh\ntsr watch\n```\n\nWith file-based routing enabled, whenever you start your application in development mode, TanStack Router will watch your configured `routesDirectory` and generate your route tree whenever a file is added, removed, or changed.\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router CLI for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by creating a `tsr.config.json` file in the root of your project directory.\n\n[//]: # 'TargetConfiguration'\n[//]: # 'TargetConfiguration'\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Rspack\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Rspack** or **Rsbuild**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your configuration.\n\n```tsx\n// rsbuild.config.ts\nimport { defineConfig } from '@rsbuild/core'\nimport { pluginReact } from '@rsbuild/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/rspack'\n\nexport default defineConfig({\n plugins: [pluginReact()],\n tools: {\n rspack: {\n plugins: [\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n ],\n },\n },\n})\n```\n\nOr, you can clone our [Quickstart Rspack/Rsbuild example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-rspack-file-based) and get started.\n\nNow that you've added the plugin to your Rspack/Rsbuild configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Rspack (or Rsbuild) for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Vite\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Vite**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your Vite configuration.\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\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n react(),\n // ...\n ],\n})\n```\n\nOr, you can clone our [Quickstart Vite example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-file-based) and get started.\n\n> [!WARNING]\n> If you are using the older `@tanstack/router-vite-plugin` package, you can still continue to use it, as it will be aliased to the `@tanstack/router-plugin/vite` package. However, we would recommend using the `@tanstack/router-plugin` package directly.\n\nNow that you've added the plugin to your Vite configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Vite for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Webpack\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Webpack**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your configuration.\n\n```tsx\n// webpack.config.ts\nimport { tanstackRouter } from '@tanstack/router-plugin/webpack'\n\nexport default {\n plugins: [\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n ],\n}\n```\n\nOr, you can clone our [Quickstart Webpack example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-webpack-file-based) and get started.\n\nNow that you've added the plugin to your Webpack configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Webpack for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n";
1
+ declare const _default: "# Manual Setup\n\nTo set up TanStack Router manually in a React project, follow the steps below. This gives you a bare minimum setup to get going with TanStack Router using both file-based route generation and code-based route configuration:\n\n## Using File-Based Route Generation\n\n#### Install TanStack Router, Vite Plugin, and the Router Devtools\n\n```sh\nnpm install @tanstack/react-router @tanstack/react-router-devtools\nnpm install -D @tanstack/router-plugin\n# or\npnpm add @tanstack/react-router @tanstack/react-router-devtools\npnpm add -D @tanstack/router-plugin\n# or\nyarn add @tanstack/react-router @tanstack/react-router-devtools\nyarn add -D @tanstack/router-plugin\n# or\nbun add @tanstack/react-router @tanstack/react-router-devtools\nbun add -D @tanstack/router-plugin\n# or\ndeno add npm:@tanstack/react-router npm:@tanstack/router-plugin npm:@tanstack/react-router-devtools\n```\n\n#### Configure the Vite Plugin\n\n```tsx\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n react(),\n // ...,\n ],\n})\n```\n\n> [!TIP]\n> If you are not using Vite, or any of the supported bundlers, you can check out the [TanStack Router CLI](../with-router-cli) guide for more info.\n\nCreate the following files:\n\n- `src/routes/__root.tsx` (with two '`_`' characters)\n- `src/routes/index.tsx`\n- `src/routes/about.tsx`\n- `src/main.tsx`\n\n#### `src/routes/__root.tsx`\n\n```tsx\nimport { createRootRoute, Link, Outlet } from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nconst RootLayout = () => (\n <>\n <div className=\"p-2 flex gap-2\">\n <Link to=\"/\" className=\"[&.active]:font-bold\">\n Home\n </Link>{' '}\n <Link to=\"/about\" className=\"[&.active]:font-bold\">\n About\n </Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n)\n\nexport const Route = createRootRoute({ component: RootLayout })\n```\n\n#### `src/routes/index.tsx`\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: Index,\n})\n\nfunction Index() {\n return (\n <div className=\"p-2\">\n <h3>Welcome Home!</h3>\n </div>\n )\n}\n```\n\n#### `src/routes/about.tsx`\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/about')({\n component: About,\n})\n\nfunction About() {\n return <div className=\"p-2\">Hello from About!</div>\n}\n```\n\n#### `src/main.tsx`\n\nRegardless of whether you are using the `@tanstack/router-plugin` package and running the `npm run dev`/`npm run build` scripts, or manually running the `tsr watch`/`tsr generate` commands from your package scripts, the route tree file will be generated at `src/routeTree.gen.ts`.\n\nImport the generated route tree and create a new router instance:\n\n```tsx\nimport { StrictMode } from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { RouterProvider, createRouter } from '@tanstack/react-router'\n\n// Import the generated route tree\nimport { routeTree } from './routeTree.gen'\n\n// Create a new router instance\nconst router = createRouter({ routeTree })\n\n// Register the router instance for type safety\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\n// Render the app\nconst rootElement = document.getElementById('root')!\nif (!rootElement.innerHTML) {\n const root = ReactDOM.createRoot(rootElement)\n root.render(\n <StrictMode>\n <RouterProvider router={router} />\n </StrictMode>,\n )\n}\n```\n\nIf you are working with this pattern you should change the `id` of the root `<div>` on your `index.html` file to `<div id='root'></div>`\n\n## Using Code-Based Route Configuration\n\n> [!IMPORTANT]\n> The following example shows how to configure routes using code, and for simplicity's sake is in a single file for this demo. While code-based generation allows you to declare many routes and even the router instance in a single file, we recommend splitting your routes into separate files for better organization and performance as your application grows.\n\n```tsx\nimport { StrictMode } from 'react'\nimport ReactDOM from 'react-dom/client'\nimport {\n Outlet,\n RouterProvider,\n Link,\n createRouter,\n createRoute,\n createRootRoute,\n} from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <div className=\"p-2 flex gap-2\">\n <Link to=\"/\" className=\"[&.active]:font-bold\">\n Home\n </Link>{' '}\n <Link to=\"/about\" className=\"[&.active]:font-bold\">\n About\n </Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst indexRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n component: function Index() {\n return (\n <div className=\"p-2\">\n <h3>Welcome Home!</h3>\n </div>\n )\n },\n})\n\nconst aboutRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/about',\n component: function About() {\n return <div className=\"p-2\">Hello from About!</div>\n },\n})\n\nconst routeTree = rootRoute.addChildren([indexRoute, aboutRoute])\n\nconst router = createRouter({ routeTree })\n\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\nconst rootElement = document.getElementById('app')!\nif (!rootElement.innerHTML) {\n const root = ReactDOM.createRoot(rootElement)\n root.render(\n <StrictMode>\n <RouterProvider router={router} />\n </StrictMode>,\n )\n}\n```\n\nIf you glossed over these examples or didn't understand something, we don't blame you, because there's so much more to learn to really take advantage of TanStack Router! Let's move on.\n\n# Migration from React Location\n\nBefore you begin your journey in migrating from React Location, it's important that you have a good understanding of the [Routing Concepts](../routing/routing-concepts.md) and [Design Decisions](../decisions-on-dx.md) used by TanStack Router.\n\n## Differences between React Location and TanStack Router\n\nReact Location and TanStack Router share much of same design decisions concepts, but there are some key differences that you should be aware of.\n\n- React Location uses _generics_ to infer types for routes, while TanStack Router uses _module declaration merging_ to infer types.\n- Route configuration in React Location is done using a single array of route definitions, while in TanStack Router, route configuration is done using a tree of route definitions starting with the [root route](../routing/routing-concepts.md#the-root-route).\n- [File-based routing](../routing/file-based-routing.md) is the recommended way to define routes in TanStack Router, while React Location only allows you to define routes in a single file using a code-based approach.\n - TanStack Router does support a [code-based approach](../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../decisions-on-dx.md#why-is-file-based-routing-the-preferred-way-to-define-routes)\n\n## Migration guide\n\nIn this guide we'll go over the process of migrating the [React Location Basic example](https://github.com/TanStack/router/tree/react-location/examples/basic) over to TanStack Router using file-based routing, with the end goal of having the same functionality as the original example (styling and other non-routing related code will be omitted).\n\n> [!TIP]\n> To use a code-based approach for defining your routes, you can read the [code-based Routing](../routing/code-based-routing.md) guide.\n\n### Step 1: Swap over to TanStack Router's dependencies\n\nFirst, we need to install the dependencies for TanStack Router. For detailed installation instructions, see our [How to Install TanStack Router](../how-to/install.md) guide.\n\n```sh\nnpm install @tanstack/react-router @tanstack/router-devtools\n```\n\nAnd remove the React Location dependencies.\n\n```sh\nnpm uninstall @tanstack/react-location @tanstack/react-location-devtools\n```\n\n### Step 2: Use the file-based routing watcher\n\nIf your project uses Vite (or one of the supported bundlers), you can use the TanStack Router plugin to watch for changes in your routes files and automatically update the routes configuration.\n\nInstallation of the Vite plugin:\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nAnd add it to your `vite.config.js`:\n\n```js\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\n\nexport default defineConfig({\n // ...\n plugins: [tanstackRouter(), react()],\n})\n```\n\nHowever, if your application does not use Vite, you use one of our other [supported bundlers](../routing/file-based-routing.md#getting-started-with-file-based-routing), or you can use the `@tanstack/router-cli` package to watch for changes in your routes files and automatically update the routes configuration.\n\n### Step 3: Add the file-based configuration file to your project\n\nCreate a `tsr.config.json` file in the root of your project with the following content:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\"\n}\n```\n\nYou can find the full list of options for the `tsr.config.json` file [here](../../../api/file-based-routing.md).\n\n### Step 4: Create the routes directory\n\nCreate a `routes` directory in the `src` directory of your project.\n\n```sh\nmkdir src/routes\n```\n\n### Step 5: Create the root route file\n\n```tsx\n// src/routes/__root.tsx\nimport { createRootRoute, Outlet, Link } from '@tanstack/react-router'\nimport { TanStackRouterDevtools } from '@tanstack/router-devtools'\n\nexport const Route = createRootRoute({\n component: () => {\n return (\n <>\n <div>\n <Link to=\"/\" activeOptions={{ exact: true }}>\n Home\n </Link>\n <Link to=\"/posts\">Posts</Link>\n </div>\n <hr />\n <Outlet />\n <TanStackRouterDevtools />\n </>\n )\n },\n})\n```\n\n### Step 6: Create the index route file\n\n```tsx\n// src/routes/index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: Index,\n})\n```\n\n> You will need to move any related components and logic needed for the index route from the `src/index.tsx` file to the `src/routes/index.tsx` file.\n\n### Step 7: Create the posts route file\n\n```tsx\n// src/routes/posts.tsx\nimport { createFileRoute, Link, Outlet } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts')({\n component: Posts,\n loader: async () => {\n const posts = await fetchPosts()\n return {\n posts,\n }\n },\n})\n\nfunction Posts() {\n const { posts } = Route.useLoaderData()\n return (\n <div>\n <nav>\n {posts.map((post) => (\n <Link\n key={post.id}\n to={`/posts/$postId`}\n params={{ postId: post.id }}\n >\n {post.title}\n </Link>\n ))}\n </nav>\n <Outlet />\n </div>\n )\n}\n```\n\n> You will need to move any related components and logic needed for the posts route from the `src/index.tsx` file to the `src/routes/posts.tsx` file.\n\n### Step 8: Create the posts index route file\n\n```tsx\n// src/routes/posts.index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/')({\n component: PostsIndex,\n})\n```\n\n> You will need to move any related components and logic needed for the posts index route from the `src/index.tsx` file to the `src/routes/posts.index.tsx` file.\n\n### Step 9: Create the posts id route file\n\n```tsx\n// src/routes/posts.$postId.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/$postId')({\n component: PostsId,\n loader: async ({ params: { postId } }) => {\n const post = await fetchPost(postId)\n return {\n post,\n }\n },\n})\n\nfunction PostsId() {\n const { post } = Route.useLoaderData()\n // ...\n}\n```\n\n> You will need to move any related components and logic needed for the posts id route from the `src/index.tsx` file to the `src/routes/posts.$postId.tsx` file.\n\n### Step 10: Generate the route tree\n\nIf you are using one of the supported bundlers, the route tree will be generated automatically when you run the dev script.\n\nIf you are not using one of the supported bundlers, you can generate the route tree by running the following command:\n\n```sh\nnpx tsr generate\n```\n\n### Step 11: Update the main entry file to render the Router\n\nOnce you've generated the route-tree, you can then update the `src/index.tsx` file to create the router instance and render it.\n\n```tsx\n// src/index.tsx\nimport React from 'react'\nimport ReactDOM from 'react-dom'\nimport { createRouter, RouterProvider } from '@tanstack/react-router'\n\n// Import the generated route tree\nimport { routeTree } from './routeTree.gen'\n\n// Create a new router instance\nconst router = createRouter({ routeTree })\n\n// Register the router instance for type safety\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n\nconst domElementId = 'root' // Assuming you have a root element with the id 'root'\n\n// Render the app\nconst rootElement = document.getElementById(domElementId)\nif (!rootElement) {\n throw new Error(`Element with id ${domElementId} not found`)\n}\n\nReactDOM.createRoot(rootElement).render(\n <React.StrictMode>\n <RouterProvider router={router} />\n </React.StrictMode>,\n)\n```\n\n### Finished!\n\nYou should now have successfully migrated your application from React Location to TanStack Router using file-based routing.\n\nReact Location also has a few more features that you might be using in your application. Here are some guides to help you migrate those features:\n\n- [Search params](../guide/search-params.md)\n- [Data loading](../guide/data-loading.md)\n- [History types](../guide/history-types.md)\n- [Wildcard / Splat / Catch-all routes](../routing/routing-concepts.md#splat--catch-all-routes)\n- [Authenticated routes](../guide/authenticated-routes.md)\n\nTanStack Router also has a few more features that you might want to explore:\n\n- [Router Context](../guide/router-context.md)\n- [Preloading](../guide/preloading.md)\n- [Pathless Layout Routes](../routing/routing-concepts.md#pathless-layout-routes)\n- [Route masking](../guide/route-masking.md)\n- [SSR](../guide/ssr.md)\n- ... and more!\n\nIf you are facing any issues or have any questions, feel free to ask for help in the TanStack Discord.\n\n# Migration from React Router Checklist\n\n**_If your UI is blank, open the console, and you will probably have some errors that read something along the lines of `cannot use 'useNavigate' outside of context` . This means there are React Router api\u2019s that are still imported and referenced that you need to find and remove. The easiest way to make sure you find all React Router imports is to uninstall `react-router-dom` and then you should get typescript errors in your files. Then you will know what to change to a `@tanstack/react-router` import._**\n\nHere is the [example repo](https://github.com/Benanna2019/SickFitsForEveryone/tree/migrate-to-tanstack/router/React-Router)\n\n- [ ] Install Router - `npm i @tanstack/react-router` (see [detailed installation guide](../how-to/install.md))\n- [ ] **Optional:** Uninstall React Router to get TypeScript errors on imports.\n - At this point I don\u2019t know if you can do a gradual migration, but it seems likely you could have multiple router providers, not desirable.\n - The api\u2019s between React Router and TanStack Router are very similar and could most likely be handled in a sprint cycle or two if that is your companies way of doing things.\n- [ ] Create Routes for each existing React Router route we have\n- [ ] Create root route\n- [ ] Create router instance\n- [ ] Add global module in main.tsx\n- [ ] Remove any React Router (`createBrowserRouter` or `BrowserRouter`), `Routes`, and `Route` Components from main.tsx\n- [ ] **Optional:** Refactor `render` function for custom setup/providers - The repo referenced above has an example - This was necessary in the case of Supertokens. Supertoken has a specific setup with React Router and a different setup with all other React implementations\n- [ ] Set RouterProvider and pass it the router as the prop\n- [ ] Replace all instances of React Router `Link` component with `@tanstack/react-router` `Link` component\n - [ ] Add `to` prop with literal path\n - [ ] Add `params` prop, where necessary with params like so `params={{ orderId: order.id }}`\n- [ ] Replace all instances of React Router `useNavigate` hook with `@tanstack/react-router` `useNavigate` hook\n - [ ] Set `to` property and `params` property where needed\n- [ ] Replace any React Router `Outlet`'s with the `@tanstack/react-router` equivalent\n- [ ] If you are using `useSearchParams` hook from React Router, move the search params default value to the validateSearch property on a Route definition.\n - [ ] Instead of using the `useSearchParams` hook, use `@tanstack/react-router` `Link`'s search property to update the search params state\n - [ ] To read search params you can do something like the following\n - `const { page } = useSearch({ from: productPage.fullPath })`\n- [ ] If using React Router\u2019s `useParams` hook, update the import to be from `@tanstack/react-router` and set the `from` property to the literal path name where you want to read the params object from\n - So say we have a route with the path name `orders/$orderid`.\n - In the `useParams` hook we would set up our hook like so: `const params = useParams({ from: \"/orders/$orderId\" })`\n - Then wherever we wanted to access the order id we would get it off of the params object `params.orderId`\n\n# Installation with Esbuild\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Esbuild**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your configuration.\n\n```tsx\n// esbuild.config.js\nimport { tanstackRouter } from '@tanstack/router-plugin/esbuild'\n\nexport default {\n // ...\n plugins: [\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n ],\n}\n```\n\nOr, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-esbuild-file-based) and get started.\n\nNow that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Esbuild for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Router CLI\n\n> [!WARNING]\n> You should only use the TanStack Router CLI if you are not using a supported bundler. The CLI only supports the generation of the route tree file and does not provide any other features.\n\nTo use file-based routing with the TanStack Router CLI, you'll need to install the `@tanstack/router-cli` package.\n\n```sh\nnpm install -D @tanstack/router-cli\n```\n\nOnce installed, you'll need to amend your scripts in your `package.json` for the CLI to `watch` and `generate` files.\n\n```json\n{\n \"scripts\": {\n \"generate-routes\": \"tsr generate\",\n \"watch-routes\": \"tsr watch\",\n \"build\": \"npm run generate-routes && ...\",\n \"dev\": \"npm run watch-routes && ...\"\n }\n}\n```\n\n[//]: # 'AfterScripts'\n[//]: # 'AfterScripts'\n\nYou shouldn't forget to _ignore_ the generated route tree file. Head over to the [Ignoring the generated route tree file](#ignoring-the-generated-route-tree-file) section to learn more.\n\nWith the CLI installed, the following commands are made available via the `tsr` command\n\n## Using the `generate` command\n\nGenerates the routes for a project based on the provided configuration.\n\n```sh\ntsr generate\n```\n\n## Using the `watch` command\n\nContinuously watches the specified directories and regenerates routes as needed.\n\n**Usage:**\n\n```sh\ntsr watch\n```\n\nWith file-based routing enabled, whenever you start your application in development mode, TanStack Router will watch your configured `routesDirectory` and generate your route tree whenever a file is added, removed, or changed.\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router CLI for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by creating a `tsr.config.json` file in the root of your project directory.\n\n[//]: # 'TargetConfiguration'\n[//]: # 'TargetConfiguration'\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Rspack\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Rspack** or **Rsbuild**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your configuration.\n\n```tsx\n// rsbuild.config.ts\nimport { defineConfig } from '@rsbuild/core'\nimport { pluginReact } from '@rsbuild/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/rspack'\n\nexport default defineConfig({\n plugins: [pluginReact()],\n tools: {\n rspack: {\n plugins: [\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n ],\n },\n },\n})\n```\n\nOr, you can clone our [Quickstart Rspack/Rsbuild example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-rspack-file-based) and get started.\n\nNow that you've added the plugin to your Rspack/Rsbuild configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Rspack (or Rsbuild) for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Vite\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Vite**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your Vite configuration.\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\n// https://vitejs.dev/config/\nexport default defineConfig({\n plugins: [\n // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n react(),\n // ...\n ],\n})\n```\n\nOr, you can clone our [Quickstart Vite example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-file-based) and get started.\n\n> [!WARNING]\n> If you are using the older `@tanstack/router-vite-plugin` package, you can still continue to use it, as it will be aliased to the `@tanstack/router-plugin/vite` package. However, we would recommend using the `@tanstack/router-plugin` package directly.\n\nNow that you've added the plugin to your Vite configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Vite for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n# Installation with Webpack\n\n[//]: # 'BundlerConfiguration'\n\nTo use file-based routing with **Webpack**, you'll need to install the `@tanstack/router-plugin` package.\n\n```sh\nnpm install -D @tanstack/router-plugin\n```\n\nOnce installed, you'll need to add the plugin to your configuration.\n\n```tsx\n// webpack.config.ts\nimport { tanstackRouter } from '@tanstack/router-plugin/webpack'\n\nexport default {\n plugins: [\n tanstackRouter({\n target: 'react',\n autoCodeSplitting: true,\n }),\n ],\n}\n```\n\nOr, you can clone our [Quickstart Webpack example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-webpack-file-based) and get started.\n\nNow that you've added the plugin to your Webpack configuration, you're all set to start using file-based routing with TanStack Router.\n\n[//]: # 'BundlerConfiguration'\n\n## Ignoring the generated route tree file\n\nIf your project is configured to use a linter and/or formatter, you may want to ignore the generated route tree file. This file is managed by TanStack Router and therefore shouldn't be changed by your linter or formatter.\n\nHere are some resources to help you ignore the generated route tree file:\n\n- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)\n- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)\n- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)\n\n> [!WARNING]\n> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.\n\nYou can prevent that from the VSCode settings by marking the file as readonly. Our recommendation is to also exclude it from search results and file watcher with the following settings:\n\n```json\n{\n \"files.readonlyInclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"files.watcherExclude\": {\n \"**/routeTree.gen.ts\": true\n },\n \"search.exclude\": {\n \"**/routeTree.gen.ts\": true\n }\n}\n```\n\nYou can use those settings either at a user level or only for a single workspace by creating the file `.vscode/settings.json` at the root of your project.\n\n## Configuration\n\nWhen using the TanStack Router Plugin with Webpack for File-based routing, it comes with some sane defaults that should work for most projects:\n\n```json\n{\n \"routesDirectory\": \"./src/routes\",\n \"generatedRouteTree\": \"./src/routeTree.gen.ts\",\n \"routeFileIgnorePrefix\": \"-\",\n \"quoteStyle\": \"single\"\n}\n```\n\nIf these defaults work for your project, you don't need to configure anything at all! However, if you need to customize the configuration, you can do so by editing the configuration object passed into the `tanstackRouter` function.\n\nYou can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).\n\n";
2
2
  export default _default;
@@ -239,7 +239,7 @@ React Location and TanStack Router share much of same design decisions concepts,
239
239
  - React Location uses _generics_ to infer types for routes, while TanStack Router uses _module declaration merging_ to infer types.
240
240
  - Route configuration in React Location is done using a single array of route definitions, while in TanStack Router, route configuration is done using a tree of route definitions starting with the [root route](../routing/routing-concepts.md#the-root-route).
241
241
  - [File-based routing](../routing/file-based-routing.md) is the recommended way to define routes in TanStack Router, while React Location only allows you to define routes in a single file using a code-based approach.
242
- - TanStack Router does support a [code-based approach](../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../decisions-on-dx.md#3-why-is-file-based-routing-the-preferred-way-to-define-routes)
242
+ - TanStack Router does support a [code-based approach](../routing/code-based-routing.md) to defining routes, but it is not recommended for most use cases. You can read more about why, over here: [why is file-based routing the preferred way to define routes?](../decisions-on-dx.md#why-is-file-based-routing-the-preferred-way-to-define-routes)
243
243
 
244
244
  ## Migration guide
245
245
 
@@ -1,2 +1,2 @@
1
- declare const _default: "# Overview\n\n**TanStack Router is a router for building React and Solid applications**. Some of its features include:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Nested Routing and layout routes (with pathless layouts)\n- Built-in Route Loaders w/ SWR Caching\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Automatic route prefetching\n- Asynchronous route elements and error boundaries\n- File-based Route Generation\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Param Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Route matching/loading middleware\n\nTo get started quickly, head to the next page. For a more lengthy explanation, buckle up while I bring you up to speed!\n\n## \"A Fork in the Route\"\n\nUsing a router to build applications is widely regarded as a must-have and is usually one of the first choices you\u2019ll make in your tech stack.\n\n## Why TanStack Router?\n\nTanStack Router delivers on the same fundamental expectations as other routers that you\u2019ve come to expect:\n\n- Nested routes, layout routes, grouped routes\n- File-based Routing\n- Parallel data loading\n- Prefetching\n- URL Path Params\n- Error Boundaries and Handling\n- SSR\n- Route Masking\n\nAnd it also delivers some new features that raise the bar:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Built-in SWR Caching for loaders\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Parameter Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Inherited Route Context\n- Mixed file-based and code-based routing\n\nLet\u2019s dive into some of the more important ones in more detail!\n\n## 100% Inferred TypeScript Support\n\nEverything these days is written \u201Cin Typescript\u201D or at the very least offers type definitions that are veneered over runtime functionality, but too few packages in the ecosystem actually design their APIs with TypeScript in mind. So while I\u2019m pleased that your router is auto-completing your option fields and catching a few property/method typos here and there, there is much more to be had.\n\n- TanStack Router is fully aware of all of your routes and their configuration at any given point in your code. This includes the path, path params, search params, context, and any other configuration you\u2019ve provided. Ultimately this means that you can navigate to any route in your app with 100% type safety and confidence that your link or navigate call will succeed.\n- TanStack Router provides lossless type-inference. It uses countless generic type parameters to enforce and propagate any type information you give it throughout the rest of its API and ultimately your app. No other router offers this level of type safety and developer confidence.\n\nWhat does all of that mean for you?\n\n- Faster feature development with auto-completion and type hints\n- Safer and faster refactors\n- Confidence that your code will work as expected\n\n## 1st Class Search Parameters\n\nSearch parameters are often an afterthought, treated like a black box of strings (or string) that you can parse and update, but not much else. Existing solutions are **not** type-safe either, adding to the caution that is required to deal with them. Even the most \"modern\" frameworks and routers leave it up to you to figure out how to manage this state. Sometimes they'll parse the search string into an object for you, or sometimes you're left to do it yourself with `URLSearchParams`.\n\nLet's step back and remember that **search params are the most powerful state manager in your entire application.** They are global, serializable, bookmarkable, and shareable making them the perfect place to store any kind of state that needs to survive a page refresh or a social share.\n\nTo live up to that responsibility, search parameters are a first-class citizen in TanStack Router. While still based on standard URLSearchParams, TanStack Router uses a powerful parser/serializer to manage deeper and more complex data structures in your search params, all while keeping them type-safe and easy to work with.\n\n**It's like having `useState` right in the URL!**\n\nSearch parameters are:\n\n- Automatically parsed and serialized as JSON\n- Validated and typed\n- Inherited from parent routes\n- Accessible in loaders, components, and hooks\n- Easily modified with the useSearch hook, Link, navigate, and router.navigate APIs\n- Customizable with a custom search filters and middleware\n- Subscribed via fine-grained search param selectors for efficient re-renders\n\nOnce you start using TanStack Router's search parameters, you'll wonder how you ever lived without them.\n\n## Built-In Caching and Friendly Data Loading\n\nData loading is a critical part of any application and while most existing routers offer some form of critical data loading APIs, they often fall short when it comes to caching and data lifecycle management. Existing solutions suffer from a few common problems:\n\n- No caching at all. Data is always fresh, but your users are left waiting for frequently accessed data to load over and over again.\n- Overly-aggressive caching. Data is cached for too long, leading to stale data and a poor user experience.\n- Blunt invalidation strategies and APIs. Data may be invalidated too often, leading to unnecessary network requests and wasted resources, or you may not have any fine-grained control over when data is invalidated at all.\n\nTanStack Router solves these problems with a two-prong approach to caching and data loading:\n\n### Built-in Cache\n\nTanStack Router provides a light-weight built-in caching layer that works seamlessly with the Router. This caching layer is loosely based on TanStack Query, but with fewer features and a much smaller API surface area. Like TanStack Query, sane but powerful defaults guarantee that your data is cached for reuse, invalidated when necessary, and garbage collected when not in use. It also provides a simple API for invalidating the cache manually when needed.\n\n### Flexible & Powerful Data Lifecycle APIs\n\nTanStack Router is designed with a flexible and powerful data loading API that more easily integrates with existing data fetching libraries like TanStack Query, SWR, Apollo, Relay, or even your own custom data fetching solution. Configurable APIs like `context`, `beforeLoad`, `loaderDeps` and `loader` work in unison to make it easy to define declarative data dependencies, prefetch data, and manage the lifecycle of an external data source with ease.\n\n## Inherited Route Context\n\nTanStack Router's router and route context is a powerful feature that allows you to define context that is specific to a route which is then inherited by all child routes. Even the router and root routes themselves can provide context. Context can be built up both synchronously and asynchronously, and can be used to share data, configuration, or even functions between routes and route configurations. This is especially useful for scenarios like:\n\n- Authentication and Authorization\n- Hybrid SSR/CSR data fetching and preloading\n- Theming\n- Singletons and global utilities\n- Curried or partial application across preloading, loading, and rendering stages\n\nAlso, what would route context be if it weren't type-safe? TanStack Router's route context is fully type-safe and inferred at zero cost to you.\n\n## File-based and/or Code-Based Routing\n\nTanStack Router supports both file-based and code-based routing at the same time. This flexibility allows you to choose the approach that best fits your project's needs.\n\nTanStack Router's file-based routing approach is uniquely user-facing. Route configuration is generated for you either by the Vite plugin or TanStack Router CLI, leaving the usage of said generated code up to you! This means that you're always in total control of your routes and router, even if you use file-based routing.\n\n## Acknowledgements\n\nTanStack Router builds on concepts and patterns popularized by many other OSS projects, including:\n\n- [TRPC](https://trpc.io/)\n- [Remix](https://remix.run)\n- [Chicane](https://swan-io.github.io/chicane/)\n- [Next.js](https://nextjs.org)\n\nWe acknowledge the investment, risk and research that went into their development, but are excited to push the bar they have set even higher.\n\n## Let's go!\n\nEnough overview, there's so much more to do with TanStack Router. Hit that next button and let's get started!\n\n# Quick Start\n\nTanStack Router can be quickly added to any existing React project or used to scaffold a new one.\n\n## TanStack Router Installation\n\n### Requirements\n\nBefore installing TanStack router, please ensure your project meets the following requirements:\n\n[//]: # 'Requirements'\n\n- `react` v18 or later with `createRoot` support.\n- `react-dom` v18 or later.\n\n[//]: # 'Requirements'\n\n> [!NOTE] Using TypeScript (`v5.3.x or higher`) is recommended for the best development experience, though not strictly required. We aim to support the last 5 minor versions of TypeScript, but using the latest version will help avoid potential issues.\n\nTanStack Router is currently only compatible with React (with ReactDOM) and Solid. If you're interested in contributing to support other frameworks, such as React Native, Angular, or Vue, please reach out to us on [Discord](https://tlinz.com/discord).\n\n### Download and Install\n\nTo install TanStack Router in your project, run the following command using your preferred package manager:\n\n[//]: # 'installCommand'\n\n```sh\nnpm install @tanstack/react-router\n# or\npnpm add @tanstack/react-router\n#or\nyarn add @tanstack/react-router\n# or\nbun add @tanstack/react-router\n# or\ndeno add npm:@tanstack/react-router\n```\n\n[//]: # 'installCommand'\n\nOnce installed, you can verify the installation by checking your `package.json` file for the dependency.\n\n[//]: # 'packageJson'\n\n```json\n{\n \"dependencies\": {\n \"@tanstack/react-router\": \"^x.x.x\"\n }\n}\n```\n\n[//]: # 'packageJson'\n\n## New Project Setup\n\nTo quickly scaffold a new project with TanStack Router, you can use the `create-tsrouter-app` command-line tool. This tool sets up a new React application with TanStack Router pre-configured, allowing you to get started quickly.\n\n> [!TIP] For full details on available options and templates, visit the [`create-tsrouter-app` documentation](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app).\n\nTo create a new project, run the following command in your terminal:\n\n[//]: # 'createAppCommand'\n\n```sh\nnpx create-tsrouter-app@latest\n```\n\n[//]: # 'createAppCommand'\n\nThe CLI will guide you through a short series of prompts to customize your setup, including options for:\n\n[//]: # 'CLIPrompts'\n\n- File-based or code-based route configuration\n- TypeScript support\n- Tailwind CSS integration\n- Toolchain setup\n- Git initialization\n\n[//]: # 'CLIPrompts'\n\nOnce complete, a new React project will be generated with TanStack Router installed and ready to use. All dependencies are automatically installed, so you can jump straight into development:\n\n```sh\ncd your-project-name\nnpm run dev\n```\n\n### Routing Options\n\nTanStack Router supports both file-based and code-based route configurations, allowing you to choose the approach that best fits your workflow.\n\n#### File-Based Route Generation\n\nThe file-based approach is the recommended option for most projects. It automatically creates routes based on your file structure, giving you the best mix of performance, simplicity, and developer experience.\n\nTo create a new project using file-based route generation, run the following command:\n\n[//]: # 'createAppCommandFileBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app --template file-router\n```\n\n[//]: # 'createAppCommandFileBased'\n\nThis command sets up a new directory called `my-app` with everything configured. Once setup completes, you can then start your development server and begin building your application:\n\n```sh\ncd my-app\nnpm run dev\n```\n\n#### Code-Based Route Configuration\n\nIf you prefer to define routes programmatically, you can use the code-based route configuration. This approach gives you full control over routing logic while maintaining the same project scaffolding workflow.\n\n[//]: # 'createAppCommandCodeBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app\n```\n\n[//]: # 'createAppCommandCodeBased'\n\nSimilar to the file-based setup, this command creates a new directory called `my-app` with TanStack Router configured for code-based routing. After setup, navigate to your project directory and start the development server:\n\n```sh\ncd my-app\nnpm run dev\n```\n\nWith either approach, you can now start building your React application with TanStack Router!\n\n# Decisions on Developer Experience\n\nWhen people first start using TanStack Router, they often have a lot of questions that revolve around the following themes:\n\n> Why do I have to do things this way?\n\n> Why is it done this way? and not that way?\n\n> I'm used to doing it this way, why should I change?\n\nAnd they are all valid questions. For the most part, people are used to using routing libraries that are very similar to each other. They all have a similar API, similar concepts, and similar ways of doing things.\n\nBut TanStack Router is different. It's not your average routing library. It's not your average state management library. It's not your average anything.\n\n## TanStack Router's origin story\n\nIt's important to remember that TanStack Router's origins stem from [Nozzle.io](https://nozzle.io)'s need for a client-side routing solution that offered a first-in-class _URL Search Parameters_ experience without compromising on the **_type-safety_** that was required to power its complex dashboards.\n\nAnd so, from TanStack Router's very inception, every facet of its design was meticulously thought out to ensure that its type-safety and developer experience were second to none.\n\n## How does TanStack Router achieve this?\n\n> TypeScript! TypeScript! TypeScript!\n\nEvery aspect of TanStack Router is designed to be as type-safe as possible, and this is achieved by leveraging TypeScript's type system to its fullest extent. This involves using some very advanced and complex types, type inference, and other features to ensure that the developer experience is as smooth as possible.\n\nBut to achieve this, we had to make some decisions that deviate from the norms in the routing world.\n\n1. [**Route configuration boilerplate?**](#1-why-is-the-routers-configuration-done-this-way): You have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n2. [**TypeScript module declaration for the router?**](#2-declaring-the-router-instance-for-type-inference): You have to pass the `Router` instance to the rest of your application using TypeScript's module declaration.\n3. [**Why push for file-based routing over code-based?**](#3-why-is-file-based-routing-the-preferred-way-to-define-routes): We push for file-based routing as the preferred way to define your routes.\n\n> TLDR; All the design decisions in the developer experience of using TanStack Router are made so that you can have a best-in-class type-safety experience without compromising on the control, flexibility, and maintainability of your route configurations.\n\n## 1. Why is the Router's configuration done this way?\n\nWhen you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible.\n\nThis means that you have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n\n> Can I use JSX to define my routes?\n\nUsing JSX for defining your routes is **out of the question**, as TypeScript will not be able to infer the route configuration types of your router.\n\n```tsx\n// \u26D4\uFE0F This is not possible\nfunction App() {\n return (\n <Router>\n <Route path=\"/posts\" component={PostsPage} />\n <Route path=\"/posts/$postId\" component={PostIdPage} />\n {/* ... */}\n </Router>\n // ^? TypeScript cannot infer the routes in this configuration\n )\n}\n```\n\nAnd since this would mean that you'd have to manually type the `to` prop of the `<Link>` component and wouldn't catch any errors until runtime, it's not a viable option.\n\n> Maybe I could define my routes as a tree of nested objects?\n\n```tsx\n// \u26D4\uFE0F This file will just keep growing and growing...\nconst router = createRouter({\n routes: {\n posts: {\n component: PostsPage, // /posts\n children: {\n $postId: {\n component: PostIdPage, // /posts/$postId\n },\n },\n },\n // ...\n },\n})\n```\n\nAt first glance, this seems like a good idea. It's easy to visualize the entire route hierarchy in one go. But this approach has a couple of big downsides that make it not ideal for large applications:\n\n- **It's not very scalable**: As your application grows, the tree will grow and become harder to manage. And since it's all defined in one file, it can become very hard to maintain.\n- **It's not great for code-splitting**: You'd have to manually code-split each component and then pass it into the `component` property of the route, further complicating the route configuration with an ever-growing route configuration file.\n\nThis only gets worse as you begin to use more features of the router, such as nested context, loaders, search param validation, etc.\n\n> So, what's the best way to define my routes?\n\nWhat we found to be the best way to define your routes is to abstract the definition of the route configuration outside of the route-tree. Then stitch together your route configurations into a single cohesive route-tree that is then passed into the `createRouter` function.\n\nYou can read more about [code-based routing](../routing/code-based-routing.md) to see how to define your routes in this way.\n\n> [!TIP]\n> Finding Code-based routing to be a bit too cumbersome? See why [file-based routing](#3-why-is-file-based-routing-the-preferred-way-to-define-routes) is the preferred way to define your routes.\n\n## 2. Declaring the Router instance for type inference\n\n> Why do I have to declare the `Router`?\n\n> This declaration stuff is way too complicated for me...\n\nOnce you've constructed your routes into a tree and passed it into your Router instance (using `createRouter`) with all the generics working correctly, you then need to somehow pass this information to the rest of your application.\n\nThere were two approaches we considered for this:\n\n1. **Imports**: You could import the `Router` instance from the file where you created it and use it directly in your components.\n\n```tsx\nimport { router } from '@/src/app'\nexport const PostsIdLink = () => {\n return (\n <Link<typeof router> to=\"/posts/$postId\" params={{ postId: '123' }}>\n Go to post 123\n </Link>\n )\n}\n```\n\nA downside to this approach is that you'd have to import the entire `Router` instance into every file where you want to use it. This can lead to increased bundle sizes and can be cumbersome to manage, and only get worse as your application grows and you use more features of the router.\n\n2. **Module declaration**: You can use TypeScript's module declaration to declare the `Router` instance as a module that can be used for type inference anywhere in your application without having to import it.\n\nYou'll do this once in your application.\n\n```tsx\n// src/app.tsx\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n```\n\nAnd then you can benefit from its auto-complete anywhere in your app without having to import it.\n\n```tsx\nexport const PostsIdLink = () => {\n return (\n <Link\n to=\"/posts/$postId\"\n // ^? TypeScript will auto-complete this for you\n params={{ postId: '123' }} // and this too!\n >\n Go to post 123\n </Link>\n )\n}\n```\n\nWe went with **module declaration**, as it is what we found to be the most scalable and maintainable approach with the least amount of overhead and boilerplate.\n\n## 3. Why is file-based routing the preferred way to define routes?\n\n> Why are the docs pushing for file-based routing?\n\n> I'm used to defining my routes in a single file, why should I change?\n\nSomething you'll notice (quite soon) in the TanStack Router documentation is that we push for **file-based routing** as the preferred method for defining your routes. This is because we've found that file-based routing is the most scalable and maintainable way to define your routes.\n\n> [!TIP]\n> Before you continue, it's important you have a good understanding of [code-based routing](../routing/code-based-routing.md) and [file-based routing](../routing/file-based-routing.md).\n\nAs mentioned in the beginning, TanStack Router was designed for complex applications that require a high degree of type-safety and maintainability. And to achieve this, the configuration of the router has been done in a precise way that allows TypeScript to infer the types of your routes as much as possible.\n\nA key difference in the set-up of a _basic_ application with TanStack Router, is that your route configurations require a function to be provided to `getParentRoute`, that returns the parent route of the current route.\n\n```tsx\nimport { createRoute } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n```\n\nAt this stage, this is done so the definition of `postsIndexRoute` can be aware of its location in the route tree and so that it can correctly infer the types of the `context`, `path params`, `search params` returned by the parent route. Incorrectly defining the `getParentRoute` function means that the properties of the parent route will not be correctly inferred by the child route.\n\nAs such, this is a critical part of the route configuration and a point of failure if not done correctly.\n\nBut this is only one part of setting up a basic application. TanStack Router requires all the routes (including the root route) to be stitched into a **_route-tree_** so that it may be passed into the `createRouter` function before declaring the `Router` instance on the module for type inference. This is another critical part of the route configuration and a point of failure if not done correctly.\n\n> \uD83E\uDD2F If this route-tree were in its own file for an application with ~40-50 routes, it can easily grow up to 700+ lines.\n\n```tsx\nconst routeTree = rootRoute.addChildren([\n postsRoute.addChildren([postsIndexRoute, postsIdRoute]),\n])\n```\n\nThis complexity only increases as you begin to use more features of the router, such as nested context, loaders, search param validation, etc. As such, it no longer becomes feasible to define your routes in a single file. And so, users end up building their own _semi consistent_ way of defining their routes across multiple files. This can lead to inconsistencies and errors in the route configuration.\n\nFinally, comes the issue of code-splitting. As your application grows, you'll want to code-split your components to reduce the initial bundle size of your application. This can be a bit of a headache to manage when you're defining your routes in a single file or even across multiple files.\n\n```tsx\nimport { createRoute, lazyRouteComponent } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n component: lazyRouteComponent(() => import('../page-components/posts/index')),\n})\n```\n\nAll of this boilerplate, no matter how essential for providing a best-in-class type-inference experience, can be a bit overwhelming and can lead to inconsistencies and errors in the route configuration.\n\n... and this example configuration is just for rendering a single codes-split route. Imagine having to do this for 40-50 routes. Now remember that you still haven't touched the `context`, `loaders`, `search param validation`, and other features of the router \uD83E\uDD15.\n\n> So, why's file-based routing the preferred way?\n\nTanStack Router's file-based routing is designed to solve all of these issues. It allows you to define your routes in a predictable way that is easy to manage and maintain, and is scalable as your application grows.\n\nThe file-based routing approach is powered by the TanStack Router Bundler Plugin. It performs 3 essential tasks that solve the pain points in route configuration when using code-based routing:\n\n1. **Route configuration boilerplate**: It generates the boilerplate for your route configurations.\n2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function match the routes with their parent routes.\n3. **Code-splitting**: It automatically code-splits your route content components and updates the route configurations with the correct component. Additionally, at runtime, it ensures that the correct component is loaded when the route is visited.\n\nLet's take a look at how the route configuration for the previous example would look like with file-based routing.\n\n```tsx\n// src/routes/posts/index.ts\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/')({\n component: () => 'Posts index component goes here!!!',\n})\n```\n\nThat's it! No need to worry about defining the `getParentRoute` function, stitching together the route-tree, or code-splitting your components. The TanStack Router Bundler Plugin handles all of this for you.\n\nAt no point does the TanStack Router Bundler Plugin take away your control over your route configurations. It's designed to be as flexible as possible, allowing you to define your routes in a way that suits your application whilst reducing the boilerplate and complexity of the route configuration.\n\nCheck out the guides for [file-based routing](../routing/file-based-routing.md) and [code-splitting](../guide/code-splitting.md) for a more in-depth explanation of how they work in TanStack Router.\n\n# Devtools\n\n> Link, take this sword... I mean Devtools!... to help you on your way!\n\nWave your hands in the air and shout hooray because TanStack Router comes with dedicated devtools! \uD83E\uDD73\n\nWhen you begin your TanStack Router journey, you'll want these devtools by your side. They help visualize all of the inner workings of TanStack Router and will likely save you hours of debugging if you find yourself in a pinch!\n\n## Installation\n\nThe devtools are a separate package that you need to install:\n\n```sh\nnpm install @tanstack/react-router-devtools\n```\n\nor\n\n```sh\npnpm add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nyarn add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nbun add @tanstack/react-router-devtools\n```\n\n## Import the Devtools\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n```\n\n## Using Devtools in production\n\nThe Devtools, if imported as `TanStackRouterDevtools` will not be shown in production. If you want to have devtools in an environment with `process.env.NODE_ENV === 'production'`, use instead `TanStackRouterDevtoolsInProd`, which has all the same options:\n\n```tsx\nimport { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools'\n```\n\n## Using inside of the `RouterProvider`\n\nThe easiest way for the devtools to work is to render them inside of your root route (or any other route). This will automatically connect the devtools to the router instance.\n\n```tsx\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n\nfunction App() {\n return <RouterProvider router={router} />\n}\n```\n\n## Manually passing the Router Instance\n\nIf rendering the devtools inside of the `RouterProvider` isn't your cup of tea, a `router` prop for the devtools accepts the same `router` instance you pass to the `Router` component. This makes it possible to place the devtools anywhere on the page, not just inside the provider:\n\n```tsx\nfunction App() {\n return (\n <>\n <RouterProvider router={router} />\n <TanStackRouterDevtools router={router} />\n </>\n )\n}\n```\n\n## Floating Mode\n\nFloating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.\n\nPlace the following code as high in your React app as you can. The closer it is to the root of the page, the better it will work!\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router />\n <TanStackRouterDevtools initialIsOpen={false} />\n </>\n )\n}\n```\n\n### Devtools Options\n\n- `router: Router`\n - The router instance to connect to.\n- `initialIsOpen: Boolean`\n - Set this `true` if you want the devtools to default to being open.\n- `panelProps: PropsObject`\n - Use this to add props to the panel. For example, you can add `className`, `style` (merge and override default style), etc.\n- `closeButtonProps: PropsObject`\n - Use this to add props to the close button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `toggleButtonProps: PropsObject`\n - Use this to add props to the toggle button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `position?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\"`\n - Defaults to `bottom-left`.\n - The position of the TanStack Router logo to open and close the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n- `containerElement?: string | any`\n - Use this to render the devtools inside a different type of container element for ally purposes.\n - Any string which corresponds to a valid intrinsic JSX element is allowed.\n - Defaults to 'footer'.\n\n## Fixed Mode\n\nTo control the position of the devtools, import the `TanStackRouterDevtoolsPanel`:\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n```\n\nIt can then be attached to provided shadow DOM target:\n\n```js\n<TanStackRouterDevtoolsPanel\n shadowDOMTarget={shadowContainer}\n router={router}\n/>\n```\n\nClick [here](https://tanstack.com/router/latest/docs/framework/react/examples/basic-devtools-panel) to see a live example of this in StackBlitz.\n\n## Embedded Mode\n\nEmbedded Mode will embed the devtools as a regular component in your application. You can style it however you'd like after that!\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router router={router} />\n <TanStackRouterDevtoolsPanel\n router={router}\n style={styles}\n className={className}\n />\n </>\n )\n}\n```\n\n### DevtoolsPanel Options\n\n- `router: Router`\n - The router instance to connect to.\n- `style: StyleObject`\n - The standard React style object used to style a component with inline styles.\n- `className: string`\n - The standard React className property used to style a component with classes.\n- `isOpen?: boolean`\n - A boolean variable indicating whether the panel is open or closed.\n- `setIsOpen?: (isOpen: boolean) => void`\n - A function that toggles the open and close state of the panel.\n- `handleDragStart?: (e: any) => void`\n - Handles the opening and closing the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n\n# Frequently Asked Questions\n\nWelcome to the TanStack Router FAQ! Here you'll find answers to common questions about the TanStack Router. If you have a question that isn't answered here, please feel free to ask in the [TanStack Discord](https://tlinz.com/discord).\n\n## Why should you choose TanStack Router over another router?\n\nTo answer this question, it's important to view the other options in the space. There are many alternatives to choose from, but only a couple that are widely adopted and actively maintained:\n\n- **Next.js** - Widely regarded as the leading framework for starting new React projects. Its design focuses on performance, development workflows, and cutting-edge technology. The framework's APIs and abstractions, while powerful, can sometimes present as non-standard. Rapid growth and industry adoption have resulted in a feature-rich experience, sometimes leading to a steeper learning curve and increased overhead.\n- **Remix / React Router** - Based on the historically successful React Router, Remix delivers a powerful developer and user experience. Its API and architectural vision are firmly rooted in web standards such as Request/Response, with an emphasis on adaptability across various JavaScript environments. Many of its APIs and abstractions are well-designed and have influenced more than a few of TanStack Router's APIs. However, its rigid design, the integration of type safety as an add-on, and sometimes strict adherence to platform APIs can present limitations for some developers.\n\nThese frameworks and routers have their strengths, but they also come with trade-offs that may not align with every project's needs. TanStack Router aims to strike a balance by offering routing APIs designed to improve the developer experience without sacrificing flexibility or performance.\n\n## Is TanStack Router a framework?\n\nTanStack Router itself is not a \"framework\" in the traditional sense, since it doesn't address a few other common full-stack concerns. However, TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.\nFor a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).\n\n## Should I commit my `routeTree.gen.ts` file into git?\n\nYes! Although the route tree file (i.e., `routeTree.gen.ts`) is generated by TanStack Router, it is essentially part of your application\u2019s runtime, not a build artifact. The route tree file is a critical part of your application\u2019s source code, and it is used by TanStack Router to build your application\u2019s routes at runtime.\n\nYou should commit this file into git so that other developers can use it to build your application.\n\n## Can I conditionally render the Root Route component?\n\nNo, the root route is always rendered as it is the entry point of your application.\n\nIf you need to conditionally render a route's component, this usually means that the page content needs to be different based on some condition (e.g. user authentication). For this use case, you should use a [Layout Route](../routing/routing-concepts.md#layout-routes) or a [Pathless Layout Route](../routing/routing-concepts.md#pathless-layout-routes) to conditionally render the content.\n\nYou can restrict access to these routes using a conditional check in the `beforeLoad` function of the route.\n\n<details>\n<summary>What does this look like?</summary>\n\n```tsx\n// src/routes/_pathless-layout.tsx\nimport { createFileRoute, Outlet } from '@tanstack/react-router'\nimport { isAuthenticated } from '../utils/auth'\n\nexport const Route = createFileRoute('/_pathless-layout', {\n beforeLoad: async () => {\n // Check if the user is authenticated\n const authed = await isAuthenticated()\n if (!authed) {\n // Redirect the user to the login page\n return '/login'\n }\n },\n component: PathlessLayoutRouteComponent,\n // ...\n})\n\nfunction PathlessLayoutRouteComponent() {\n return (\n <div>\n <h1>You are authed</h1>\n <Outlet />\n </div>\n )\n}\n```\n\n</details>\n\n";
1
+ declare const _default: "# Overview\n\n**TanStack Router is a router for building React and Solid applications**. Some of its features include:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Nested Routing and layout routes (with pathless layouts)\n- Built-in Route Loaders w/ SWR Caching\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Automatic route prefetching\n- Asynchronous route elements and error boundaries\n- File-based Route Generation\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Param Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Route matching/loading middleware\n\nTo get started quickly, head to the next page. For a more lengthy explanation, buckle up while I bring you up to speed!\n\n## \"A Fork in the Route\"\n\nUsing a router to build applications is widely regarded as a must-have and is usually one of the first choices you\u2019ll make in your tech stack.\n\n## Why TanStack Router?\n\nTanStack Router delivers on the same fundamental expectations as other routers that you\u2019ve come to expect:\n\n- Nested routes, layout routes, grouped routes\n- File-based Routing\n- Parallel data loading\n- Prefetching\n- URL Path Params\n- Error Boundaries and Handling\n- SSR\n- Route Masking\n\nAnd it also delivers some new features that raise the bar:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Built-in SWR Caching for loaders\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Parameter Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Inherited Route Context\n- Mixed file-based and code-based routing\n\nLet\u2019s dive into some of the more important ones in more detail!\n\n## 100% Inferred TypeScript Support\n\nEverything these days is written \u201Cin Typescript\u201D or at the very least offers type definitions that are veneered over runtime functionality, but too few packages in the ecosystem actually design their APIs with TypeScript in mind. So while I\u2019m pleased that your router is auto-completing your option fields and catching a few property/method typos here and there, there is much more to be had.\n\n- TanStack Router is fully aware of all of your routes and their configuration at any given point in your code. This includes the path, path params, search params, context, and any other configuration you\u2019ve provided. Ultimately this means that you can navigate to any route in your app with 100% type safety and confidence that your link or navigate call will succeed.\n- TanStack Router provides lossless type-inference. It uses countless generic type parameters to enforce and propagate any type information you give it throughout the rest of its API and ultimately your app. No other router offers this level of type safety and developer confidence.\n\nWhat does all of that mean for you?\n\n- Faster feature development with auto-completion and type hints\n- Safer and faster refactors\n- Confidence that your code will work as expected\n\n## 1st Class Search Parameters\n\nSearch parameters are often an afterthought, treated like a black box of strings (or string) that you can parse and update, but not much else. Existing solutions are **not** type-safe either, adding to the caution that is required to deal with them. Even the most \"modern\" frameworks and routers leave it up to you to figure out how to manage this state. Sometimes they'll parse the search string into an object for you, or sometimes you're left to do it yourself with `URLSearchParams`.\n\nLet's step back and remember that **search params are the most powerful state manager in your entire application.** They are global, serializable, bookmarkable, and shareable making them the perfect place to store any kind of state that needs to survive a page refresh or a social share.\n\nTo live up to that responsibility, search parameters are a first-class citizen in TanStack Router. While still based on standard URLSearchParams, TanStack Router uses a powerful parser/serializer to manage deeper and more complex data structures in your search params, all while keeping them type-safe and easy to work with.\n\n**It's like having `useState` right in the URL!**\n\nSearch parameters are:\n\n- Automatically parsed and serialized as JSON\n- Validated and typed\n- Inherited from parent routes\n- Accessible in loaders, components, and hooks\n- Easily modified with the useSearch hook, Link, navigate, and router.navigate APIs\n- Customizable with a custom search filters and middleware\n- Subscribed via fine-grained search param selectors for efficient re-renders\n\nOnce you start using TanStack Router's search parameters, you'll wonder how you ever lived without them.\n\n## Built-In Caching and Friendly Data Loading\n\nData loading is a critical part of any application and while most existing routers offer some form of critical data loading APIs, they often fall short when it comes to caching and data lifecycle management. Existing solutions suffer from a few common problems:\n\n- No caching at all. Data is always fresh, but your users are left waiting for frequently accessed data to load over and over again.\n- Overly-aggressive caching. Data is cached for too long, leading to stale data and a poor user experience.\n- Blunt invalidation strategies and APIs. Data may be invalidated too often, leading to unnecessary network requests and wasted resources, or you may not have any fine-grained control over when data is invalidated at all.\n\nTanStack Router solves these problems with a two-prong approach to caching and data loading:\n\n### Built-in Cache\n\nTanStack Router provides a light-weight built-in caching layer that works seamlessly with the Router. This caching layer is loosely based on TanStack Query, but with fewer features and a much smaller API surface area. Like TanStack Query, sane but powerful defaults guarantee that your data is cached for reuse, invalidated when necessary, and garbage collected when not in use. It also provides a simple API for invalidating the cache manually when needed.\n\n### Flexible & Powerful Data Lifecycle APIs\n\nTanStack Router is designed with a flexible and powerful data loading API that more easily integrates with existing data fetching libraries like TanStack Query, SWR, Apollo, Relay, or even your own custom data fetching solution. Configurable APIs like `context`, `beforeLoad`, `loaderDeps` and `loader` work in unison to make it easy to define declarative data dependencies, prefetch data, and manage the lifecycle of an external data source with ease.\n\n## Inherited Route Context\n\nTanStack Router's router and route context is a powerful feature that allows you to define context that is specific to a route which is then inherited by all child routes. Even the router and root routes themselves can provide context. Context can be built up both synchronously and asynchronously, and can be used to share data, configuration, or even functions between routes and route configurations. This is especially useful for scenarios like:\n\n- Authentication and Authorization\n- Hybrid SSR/CSR data fetching and preloading\n- Theming\n- Singletons and global utilities\n- Curried or partial application across preloading, loading, and rendering stages\n\nAlso, what would route context be if it weren't type-safe? TanStack Router's route context is fully type-safe and inferred at zero cost to you.\n\n## File-based and/or Code-Based Routing\n\nTanStack Router supports both file-based and code-based routing at the same time. This flexibility allows you to choose the approach that best fits your project's needs.\n\nTanStack Router's file-based routing approach is uniquely user-facing. Route configuration is generated for you either by the Vite plugin or TanStack Router CLI, leaving the usage of said generated code up to you! This means that you're always in total control of your routes and router, even if you use file-based routing.\n\n## Acknowledgements\n\nTanStack Router builds on concepts and patterns popularized by many other OSS projects, including:\n\n- [TRPC](https://trpc.io/)\n- [Remix](https://remix.run)\n- [Chicane](https://swan-io.github.io/chicane/)\n- [Next.js](https://nextjs.org)\n\nWe acknowledge the investment, risk and research that went into their development, but are excited to push the bar they have set even higher.\n\n## Let's go!\n\nEnough overview, there's so much more to do with TanStack Router. Hit that next button and let's get started!\n\n# Quick Start\n\nTanStack Router can be quickly added to any existing React project or used to scaffold a new one.\n\n## TanStack Router Installation\n\n### Requirements\n\nBefore installing TanStack router, please ensure your project meets the following requirements:\n\n[//]: # 'Requirements'\n\n- `react` v18 or later with `createRoot` support.\n- `react-dom` v18 or later.\n\n[//]: # 'Requirements'\n\n> [!NOTE] Using TypeScript (`v5.3.x or higher`) is recommended for the best development experience, though not strictly required. We aim to support the last 5 minor versions of TypeScript, but using the latest version will help avoid potential issues.\n\nTanStack Router is currently only compatible with React (with ReactDOM) and Solid. If you're interested in contributing to support other frameworks, such as React Native, Angular, or Vue, please reach out to us on [Discord](https://tlinz.com/discord).\n\n### Download and Install\n\nTo install TanStack Router in your project, run the following command using your preferred package manager:\n\n[//]: # 'installCommand'\n\n```sh\nnpm install @tanstack/react-router\n# or\npnpm add @tanstack/react-router\n#or\nyarn add @tanstack/react-router\n# or\nbun add @tanstack/react-router\n# or\ndeno add npm:@tanstack/react-router\n```\n\n[//]: # 'installCommand'\n\nOnce installed, you can verify the installation by checking your `package.json` file for the dependency.\n\n[//]: # 'packageJson'\n\n```json\n{\n \"dependencies\": {\n \"@tanstack/react-router\": \"^x.x.x\"\n }\n}\n```\n\n[//]: # 'packageJson'\n\n## New Project Setup\n\nTo quickly scaffold a new project with TanStack Router, you can use the `create-tsrouter-app` command-line tool. This tool sets up a new React application with TanStack Router pre-configured, allowing you to get started quickly.\n\n> [!TIP] For full details on available options and templates, visit the [`create-tsrouter-app` documentation](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app).\n\nTo create a new project, run the following command in your terminal:\n\n[//]: # 'createAppCommand'\n\n```sh\nnpx create-tsrouter-app@latest\n```\n\n[//]: # 'createAppCommand'\n\nThe CLI will guide you through a short series of prompts to customize your setup, including options for:\n\n[//]: # 'CLIPrompts'\n\n- File-based or code-based route configuration\n- TypeScript support\n- Tailwind CSS integration\n- Toolchain setup\n- Git initialization\n\n[//]: # 'CLIPrompts'\n\nOnce complete, a new React project will be generated with TanStack Router installed and ready to use. All dependencies are automatically installed, so you can jump straight into development:\n\n```sh\ncd your-project-name\nnpm run dev\n```\n\n### Routing Options\n\nTanStack Router supports both file-based and code-based route configurations, allowing you to choose the approach that best fits your workflow.\n\n#### File-Based Route Generation\n\nThe file-based approach is the recommended option for most projects. It automatically creates routes based on your file structure, giving you the best mix of performance, simplicity, and developer experience.\n\nTo create a new project using file-based route generation, run the following command:\n\n[//]: # 'createAppCommandFileBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app --template file-router\n```\n\n[//]: # 'createAppCommandFileBased'\n\nThis command sets up a new directory called `my-app` with everything configured. Once setup completes, you can then start your development server and begin building your application:\n\n```sh\ncd my-app\nnpm run dev\n```\n\n#### Code-Based Route Configuration\n\nIf you prefer to define routes programmatically, you can use the code-based route configuration. This approach gives you full control over routing logic while maintaining the same project scaffolding workflow.\n\n[//]: # 'createAppCommandCodeBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app\n```\n\n[//]: # 'createAppCommandCodeBased'\n\nSimilar to the file-based setup, this command creates a new directory called `my-app` with TanStack Router configured for code-based routing. After setup, navigate to your project directory and start the development server:\n\n```sh\ncd my-app\nnpm run dev\n```\n\nWith either approach, you can now start building your React application with TanStack Router!\n\n# Decisions on Developer Experience\n\nWhen people first start using TanStack Router, they often have a lot of questions that revolve around the following themes:\n\n> Why do I have to do things this way?\n\n> Why is it done this way? and not that way?\n\n> I'm used to doing it this way, why should I change?\n\nAnd they are all valid questions. For the most part, people are used to using routing libraries that are very similar to each other. They all have a similar API, similar concepts, and similar ways of doing things.\n\nBut TanStack Router is different. It's not your average routing library. It's not your average state management library. It's not your average anything.\n\n## TanStack Router's origin story\n\nIt's important to remember that TanStack Router's origins stem from [Nozzle.io](https://nozzle.io)'s need for a client-side routing solution that offered a first-in-class _URL Search Parameters_ experience without compromising on the **_type-safety_** that was required to power its complex dashboards.\n\nAnd so, from TanStack Router's very inception, every facet of its design was meticulously thought out to ensure that its type-safety and developer experience were second to none.\n\n## How does TanStack Router achieve this?\n\n> TypeScript! TypeScript! TypeScript!\n\nEvery aspect of TanStack Router is designed to be as type-safe as possible, and this is achieved by leveraging TypeScript's type system to its fullest extent. This involves using some very advanced and complex types, type inference, and other features to ensure that the developer experience is as smooth as possible.\n\nBut to achieve this, we had to make some decisions that deviate from the norms in the routing world.\n\n1. [**Route configuration boilerplate?**](#why-is-the-routers-configuration-done-this-way): You have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n2. [**TypeScript module declaration for the router?**](#declaring-the-router-instance-for-type-inference): You have to pass the `Router` instance to the rest of your application using TypeScript's module declaration.\n3. [**Why push for file-based routing over code-based?**](#why-is-file-based-routing-the-preferred-way-to-define-routes): We push for file-based routing as the preferred way to define your routes.\n\n> TLDR; All the design decisions in the developer experience of using TanStack Router are made so that you can have a best-in-class type-safety experience without compromising on the control, flexibility, and maintainability of your route configurations.\n\n## Why is the Router's configuration done this way?\n\nWhen you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible.\n\nThis means that you have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n\n> Can I use JSX to define my routes?\n\nUsing JSX for defining your routes is **out of the question**, as TypeScript will not be able to infer the route configuration types of your router.\n\n```tsx\n// \u26D4\uFE0F This is not possible\nfunction App() {\n return (\n <Router>\n <Route path=\"/posts\" component={PostsPage} />\n <Route path=\"/posts/$postId\" component={PostIdPage} />\n {/* ... */}\n </Router>\n // ^? TypeScript cannot infer the routes in this configuration\n )\n}\n```\n\nAnd since this would mean that you'd have to manually type the `to` prop of the `<Link>` component and wouldn't catch any errors until runtime, it's not a viable option.\n\n> Maybe I could define my routes as a tree of nested objects?\n\n```tsx\n// \u26D4\uFE0F This file will just keep growing and growing...\nconst router = createRouter({\n routes: {\n posts: {\n component: PostsPage, // /posts\n children: {\n $postId: {\n component: PostIdPage, // /posts/$postId\n },\n },\n },\n // ...\n },\n})\n```\n\nAt first glance, this seems like a good idea. It's easy to visualize the entire route hierarchy in one go. But this approach has a couple of big downsides that make it not ideal for large applications:\n\n- **It's not very scalable**: As your application grows, the tree will grow and become harder to manage. And since it's all defined in one file, it can become very hard to maintain.\n- **It's not great for code-splitting**: You'd have to manually code-split each component and then pass it into the `component` property of the route, further complicating the route configuration with an ever-growing route configuration file.\n\nThis only gets worse as you begin to use more features of the router, such as nested context, loaders, search param validation, etc.\n\n> So, what's the best way to define my routes?\n\nWhat we found to be the best way to define your routes is to abstract the definition of the route configuration outside of the route-tree. Then stitch together your route configurations into a single cohesive route-tree that is then passed into the `createRouter` function.\n\nYou can read more about [code-based routing](../routing/code-based-routing.md) to see how to define your routes in this way.\n\n> [!TIP]\n> Finding Code-based routing to be a bit too cumbersome? See why [file-based routing](#why-is-file-based-routing-the-preferred-way-to-define-routes) is the preferred way to define your routes.\n\n## Declaring the Router instance for type inference\n\n> Why do I have to declare the `Router`?\n\n> This declaration stuff is way too complicated for me...\n\nOnce you've constructed your routes into a tree and passed it into your Router instance (using `createRouter`) with all the generics working correctly, you then need to somehow pass this information to the rest of your application.\n\nThere were two approaches we considered for this:\n\n1. **Imports**: You could import the `Router` instance from the file where you created it and use it directly in your components.\n\n```tsx\nimport { router } from '@/src/app'\nexport const PostsIdLink = () => {\n return (\n <Link<typeof router> to=\"/posts/$postId\" params={{ postId: '123' }}>\n Go to post 123\n </Link>\n )\n}\n```\n\nA downside to this approach is that you'd have to import the entire `Router` instance into every file where you want to use it. This can lead to increased bundle sizes and can be cumbersome to manage, and only get worse as your application grows and you use more features of the router.\n\n2. **Module declaration**: You can use TypeScript's module declaration to declare the `Router` instance as a module that can be used for type inference anywhere in your application without having to import it.\n\nYou'll do this once in your application.\n\n```tsx\n// src/app.tsx\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n```\n\nAnd then you can benefit from its auto-complete anywhere in your app without having to import it.\n\n```tsx\nexport const PostsIdLink = () => {\n return (\n <Link\n to=\"/posts/$postId\"\n // ^? TypeScript will auto-complete this for you\n params={{ postId: '123' }} // and this too!\n >\n Go to post 123\n </Link>\n )\n}\n```\n\nWe went with **module declaration**, as it is what we found to be the most scalable and maintainable approach with the least amount of overhead and boilerplate.\n\n## Why is file-based routing the preferred way to define routes?\n\n> Why are the docs pushing for file-based routing?\n\n> I'm used to defining my routes in a single file, why should I change?\n\nSomething you'll notice (quite soon) in the TanStack Router documentation is that we push for **file-based routing** as the preferred method for defining your routes. This is because we've found that file-based routing is the most scalable and maintainable way to define your routes.\n\n> [!TIP]\n> Before you continue, it's important you have a good understanding of [code-based routing](../routing/code-based-routing.md) and [file-based routing](../routing/file-based-routing.md).\n\nAs mentioned in the beginning, TanStack Router was designed for complex applications that require a high degree of type-safety and maintainability. And to achieve this, the configuration of the router has been done in a precise way that allows TypeScript to infer the types of your routes as much as possible.\n\nA key difference in the set-up of a _basic_ application with TanStack Router, is that your route configurations require a function to be provided to `getParentRoute`, that returns the parent route of the current route.\n\n```tsx\nimport { createRoute } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n```\n\nAt this stage, this is done so the definition of `postsIndexRoute` can be aware of its location in the route tree and so that it can correctly infer the types of the `context`, `path params`, `search params` returned by the parent route. Incorrectly defining the `getParentRoute` function means that the properties of the parent route will not be correctly inferred by the child route.\n\nAs such, this is a critical part of the route configuration and a point of failure if not done correctly.\n\nBut this is only one part of setting up a basic application. TanStack Router requires all the routes (including the root route) to be stitched into a **_route-tree_** so that it may be passed into the `createRouter` function before declaring the `Router` instance on the module for type inference. This is another critical part of the route configuration and a point of failure if not done correctly.\n\n> \uD83E\uDD2F If this route-tree were in its own file for an application with ~40-50 routes, it can easily grow up to 700+ lines.\n\n```tsx\nconst routeTree = rootRoute.addChildren([\n postsRoute.addChildren([postsIndexRoute, postsIdRoute]),\n])\n```\n\nThis complexity only increases as you begin to use more features of the router, such as nested context, loaders, search param validation, etc. As such, it no longer becomes feasible to define your routes in a single file. And so, users end up building their own _semi consistent_ way of defining their routes across multiple files. This can lead to inconsistencies and errors in the route configuration.\n\nFinally, comes the issue of code-splitting. As your application grows, you'll want to code-split your components to reduce the initial bundle size of your application. This can be a bit of a headache to manage when you're defining your routes in a single file or even across multiple files.\n\n```tsx\nimport { createRoute, lazyRouteComponent } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n component: lazyRouteComponent(() => import('../page-components/posts/index')),\n})\n```\n\nAll of this boilerplate, no matter how essential for providing a best-in-class type-inference experience, can be a bit overwhelming and can lead to inconsistencies and errors in the route configuration.\n\n... and this example configuration is just for rendering a single codes-split route. Imagine having to do this for 40-50 routes. Now remember that you still haven't touched the `context`, `loaders`, `search param validation`, and other features of the router \uD83E\uDD15.\n\n> So, why's file-based routing the preferred way?\n\nTanStack Router's file-based routing is designed to solve all of these issues. It allows you to define your routes in a predictable way that is easy to manage and maintain, and is scalable as your application grows.\n\nThe file-based routing approach is powered by the TanStack Router Bundler Plugin. It performs 3 essential tasks that solve the pain points in route configuration when using code-based routing:\n\n1. **Route configuration boilerplate**: It generates the boilerplate for your route configurations.\n2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function match the routes with their parent routes.\n3. **Code-splitting**: It automatically code-splits your route content components and updates the route configurations with the correct component. Additionally, at runtime, it ensures that the correct component is loaded when the route is visited.\n\nLet's take a look at how the route configuration for the previous example would look like with file-based routing.\n\n```tsx\n// src/routes/posts/index.ts\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/')({\n component: () => 'Posts index component goes here!!!',\n})\n```\n\nThat's it! No need to worry about defining the `getParentRoute` function, stitching together the route-tree, or code-splitting your components. The TanStack Router Bundler Plugin handles all of this for you.\n\nAt no point does the TanStack Router Bundler Plugin take away your control over your route configurations. It's designed to be as flexible as possible, allowing you to define your routes in a way that suits your application whilst reducing the boilerplate and complexity of the route configuration.\n\nCheck out the guides for [file-based routing](../routing/file-based-routing.md) and [code-splitting](../guide/code-splitting.md) for a more in-depth explanation of how they work in TanStack Router.\n\n# Devtools\n\n> Link, take this sword... I mean Devtools!... to help you on your way!\n\nWave your hands in the air and shout hooray because TanStack Router comes with dedicated devtools! \uD83E\uDD73\n\nWhen you begin your TanStack Router journey, you'll want these devtools by your side. They help visualize all of the inner workings of TanStack Router and will likely save you hours of debugging if you find yourself in a pinch!\n\n## Installation\n\nThe devtools are a separate package that you need to install:\n\n```sh\nnpm install @tanstack/react-router-devtools\n```\n\nor\n\n```sh\npnpm add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nyarn add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nbun add @tanstack/react-router-devtools\n```\n\n## Import the Devtools\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n```\n\n## Using Devtools in production\n\nThe Devtools, if imported as `TanStackRouterDevtools` will not be shown in production. If you want to have devtools in an environment with `process.env.NODE_ENV === 'production'`, use instead `TanStackRouterDevtoolsInProd`, which has all the same options:\n\n```tsx\nimport { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools'\n```\n\n## Using inside of the `RouterProvider`\n\nThe easiest way for the devtools to work is to render them inside of your root route (or any other route). This will automatically connect the devtools to the router instance.\n\n```tsx\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n\nfunction App() {\n return <RouterProvider router={router} />\n}\n```\n\n## Manually passing the Router Instance\n\nIf rendering the devtools inside of the `RouterProvider` isn't your cup of tea, a `router` prop for the devtools accepts the same `router` instance you pass to the `Router` component. This makes it possible to place the devtools anywhere on the page, not just inside the provider:\n\n```tsx\nfunction App() {\n return (\n <>\n <RouterProvider router={router} />\n <TanStackRouterDevtools router={router} />\n </>\n )\n}\n```\n\n## Floating Mode\n\nFloating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.\n\nPlace the following code as high in your React app as you can. The closer it is to the root of the page, the better it will work!\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router />\n <TanStackRouterDevtools initialIsOpen={false} />\n </>\n )\n}\n```\n\n### Devtools Options\n\n- `router: Router`\n - The router instance to connect to.\n- `initialIsOpen: Boolean`\n - Set this `true` if you want the devtools to default to being open.\n- `panelProps: PropsObject`\n - Use this to add props to the panel. For example, you can add `className`, `style` (merge and override default style), etc.\n- `closeButtonProps: PropsObject`\n - Use this to add props to the close button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `toggleButtonProps: PropsObject`\n - Use this to add props to the toggle button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `position?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\"`\n - Defaults to `bottom-left`.\n - The position of the TanStack Router logo to open and close the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n- `containerElement?: string | any`\n - Use this to render the devtools inside a different type of container element for ally purposes.\n - Any string which corresponds to a valid intrinsic JSX element is allowed.\n - Defaults to 'footer'.\n\n## Fixed Mode\n\nTo control the position of the devtools, import the `TanStackRouterDevtoolsPanel`:\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n```\n\nIt can then be attached to provided shadow DOM target:\n\n```js\n<TanStackRouterDevtoolsPanel\n shadowDOMTarget={shadowContainer}\n router={router}\n/>\n```\n\nClick [here](https://tanstack.com/router/latest/docs/framework/react/examples/basic-devtools-panel) to see a live example of this in StackBlitz.\n\n## Embedded Mode\n\nEmbedded Mode will embed the devtools as a regular component in your application. You can style it however you'd like after that!\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router router={router} />\n <TanStackRouterDevtoolsPanel\n router={router}\n style={styles}\n className={className}\n />\n </>\n )\n}\n```\n\n### DevtoolsPanel Options\n\n- `router: Router`\n - The router instance to connect to.\n- `style: StyleObject`\n - The standard React style object used to style a component with inline styles.\n- `className: string`\n - The standard React className property used to style a component with classes.\n- `isOpen?: boolean`\n - A boolean variable indicating whether the panel is open or closed.\n- `setIsOpen?: (isOpen: boolean) => void`\n - A function that toggles the open and close state of the panel.\n- `handleDragStart?: (e: any) => void`\n - Handles the opening and closing the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n\n# Frequently Asked Questions\n\nWelcome to the TanStack Router FAQ! Here you'll find answers to common questions about the TanStack Router. If you have a question that isn't answered here, please feel free to ask in the [TanStack Discord](https://tlinz.com/discord).\n\n## Why should you choose TanStack Router over another router?\n\nTo answer this question, it's important to view the other options in the space. There are many alternatives to choose from, but only a couple that are widely adopted and actively maintained:\n\n- **Next.js** - Widely regarded as the leading framework for starting new React projects. Its design focuses on performance, development workflows, and cutting-edge technology. The framework's APIs and abstractions, while powerful, can sometimes present as non-standard. Rapid growth and industry adoption have resulted in a feature-rich experience, sometimes leading to a steeper learning curve and increased overhead.\n- **Remix / React Router** - Based on the historically successful React Router, Remix delivers a powerful developer and user experience. Its API and architectural vision are firmly rooted in web standards such as Request/Response, with an emphasis on adaptability across various JavaScript environments. Many of its APIs and abstractions are well-designed and have influenced more than a few of TanStack Router's APIs. However, its rigid design, the integration of type safety as an add-on, and sometimes strict adherence to platform APIs can present limitations for some developers.\n\nThese frameworks and routers have their strengths, but they also come with trade-offs that may not align with every project's needs. TanStack Router aims to strike a balance by offering routing APIs designed to improve the developer experience without sacrificing flexibility or performance.\n\n## Is TanStack Router a framework?\n\nTanStack Router itself is not a \"framework\" in the traditional sense, since it doesn't address a few other common full-stack concerns. However, TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.\nFor a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).\n\n## Should I commit my `routeTree.gen.ts` file into git?\n\nYes! Although the route tree file (i.e., `routeTree.gen.ts`) is generated by TanStack Router, it is essentially part of your application\u2019s runtime, not a build artifact. The route tree file is a critical part of your application\u2019s source code, and it is used by TanStack Router to build your application\u2019s routes at runtime.\n\nYou should commit this file into git so that other developers can use it to build your application.\n\n## Can I conditionally render the Root Route component?\n\nNo, the root route is always rendered as it is the entry point of your application.\n\nIf you need to conditionally render a route's component, this usually means that the page content needs to be different based on some condition (e.g. user authentication). For this use case, you should use a [Layout Route](../routing/routing-concepts.md#layout-routes) or a [Pathless Layout Route](../routing/routing-concepts.md#pathless-layout-routes) to conditionally render the content.\n\nYou can restrict access to these routes using a conditional check in the `beforeLoad` function of the route.\n\n<details>\n<summary>What does this look like?</summary>\n\n```tsx\n// src/routes/_pathless-layout.tsx\nimport { createFileRoute, Outlet } from '@tanstack/react-router'\nimport { isAuthenticated } from '../utils/auth'\n\nexport const Route = createFileRoute('/_pathless-layout', {\n beforeLoad: async () => {\n // Check if the user is authenticated\n const authed = await isAuthenticated()\n if (!authed) {\n // Redirect the user to the login page\n return '/login'\n }\n },\n component: PathlessLayoutRouteComponent,\n // ...\n})\n\nfunction PathlessLayoutRouteComponent() {\n return (\n <div>\n <h1>You are authed</h1>\n <Outlet />\n </div>\n )\n}\n```\n\n</details>\n\n";
2
2
  export default _default;
@@ -302,13 +302,13 @@ Every aspect of TanStack Router is designed to be as type-safe as possible, and
302
302
 
303
303
  But to achieve this, we had to make some decisions that deviate from the norms in the routing world.
304
304
 
305
- 1. [**Route configuration boilerplate?**](#1-why-is-the-routers-configuration-done-this-way): You have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.
306
- 2. [**TypeScript module declaration for the router?**](#2-declaring-the-router-instance-for-type-inference): You have to pass the \`Router\` instance to the rest of your application using TypeScript's module declaration.
307
- 3. [**Why push for file-based routing over code-based?**](#3-why-is-file-based-routing-the-preferred-way-to-define-routes): We push for file-based routing as the preferred way to define your routes.
305
+ 1. [**Route configuration boilerplate?**](#why-is-the-routers-configuration-done-this-way): You have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.
306
+ 2. [**TypeScript module declaration for the router?**](#declaring-the-router-instance-for-type-inference): You have to pass the \`Router\` instance to the rest of your application using TypeScript's module declaration.
307
+ 3. [**Why push for file-based routing over code-based?**](#why-is-file-based-routing-the-preferred-way-to-define-routes): We push for file-based routing as the preferred way to define your routes.
308
308
 
309
309
  > TLDR; All the design decisions in the developer experience of using TanStack Router are made so that you can have a best-in-class type-safety experience without compromising on the control, flexibility, and maintainability of your route configurations.
310
310
 
311
- ## 1. Why is the Router's configuration done this way?
311
+ ## Why is the Router's configuration done this way?
312
312
 
313
313
  When you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible.
314
314
 
@@ -367,9 +367,9 @@ What we found to be the best way to define your routes is to abstract the defini
367
367
  You can read more about [code-based routing](../routing/code-based-routing.md) to see how to define your routes in this way.
368
368
 
369
369
  > [!TIP]
370
- > Finding Code-based routing to be a bit too cumbersome? See why [file-based routing](#3-why-is-file-based-routing-the-preferred-way-to-define-routes) is the preferred way to define your routes.
370
+ > Finding Code-based routing to be a bit too cumbersome? See why [file-based routing](#why-is-file-based-routing-the-preferred-way-to-define-routes) is the preferred way to define your routes.
371
371
 
372
- ## 2. Declaring the Router instance for type inference
372
+ ## Declaring the Router instance for type inference
373
373
 
374
374
  > Why do I have to declare the \`Router\`?
375
375
 
@@ -425,7 +425,7 @@ export const PostsIdLink = () => {
425
425
 
426
426
  We went with **module declaration**, as it is what we found to be the most scalable and maintainable approach with the least amount of overhead and boilerplate.
427
427
 
428
- ## 3. Why is file-based routing the preferred way to define routes?
428
+ ## Why is file-based routing the preferred way to define routes?
429
429
 
430
430
  > Why are the docs pushing for file-based routing?
431
431
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/react-router",
3
- "version": "1.133.27",
3
+ "version": "1.133.32",
4
4
  "description": "Modern and scalable routing for React applications",
5
5
  "author": "Tanner Linsley",
6
6
  "license": "MIT",
@@ -79,8 +79,8 @@
79
79
  "isbot": "^5.1.22",
80
80
  "tiny-invariant": "^1.3.3",
81
81
  "tiny-warning": "^1.0.3",
82
- "@tanstack/history": "1.133.19",
83
- "@tanstack/router-core": "1.133.27"
82
+ "@tanstack/router-core": "1.133.28",
83
+ "@tanstack/history": "1.133.28"
84
84
  },
85
85
  "devDependencies": {
86
86
  "@testing-library/jest-dom": "^6.6.3",
@@ -28,6 +28,11 @@ export interface ClientOnlyProps {
28
28
  * )
29
29
  * ```
30
30
  */
31
+ /**
32
+ * Render children only after client hydration; otherwise render `fallback`.
33
+ * Useful for components that require browser-only APIs.
34
+ * @link https://tanstack.com/router/latest/docs/framework/react/api/router/clientOnlyComponent
35
+ */
31
36
  export function ClientOnly({ children, fallback = null }: ClientOnlyProps) {
32
37
  return useHydrated() ? (
33
38
  <React.Fragment>{children}</React.Fragment>
@@ -55,6 +60,9 @@ export function ClientOnly({ children, fallback = null }: ClientOnlyProps) {
55
60
  * ```
56
61
  * @returns True if the JS has been hydrated already, false otherwise.
57
62
  */
63
+ /**
64
+ * Return a boolean indicating whether client hydration has occurred.
65
+ */
58
66
  function useHydrated(): boolean {
59
67
  return React.useSyncExternalStore(
60
68
  subscribe,
@@ -4,6 +4,10 @@ import { useRouter } from './useRouter'
4
4
  import { useRouterState } from './useRouterState'
5
5
  import type { RouterManagedTag } from '@tanstack/router-core'
6
6
 
7
+ /**
8
+ * Build the list of head/link/meta/script tags to render for active matches.
9
+ * Used internally by `HeadContent`.
10
+ */
7
11
  export const useTags = () => {
8
12
  const router = useRouter()
9
13
  const nonce = router.options.ssr?.nonce
@@ -187,6 +191,11 @@ export const useTags = () => {
187
191
  * @description The `HeadContent` component is used to render meta tags, links, and scripts for the current route.
188
192
  * It should be rendered in the `<head>` of your document.
189
193
  */
194
+ /**
195
+ * Render route-managed head tags (title, meta, links, styles, head scripts).
196
+ * Place inside the document head of your app shell.
197
+ * @link https://tanstack.com/router/latest/docs/framework/react/guide/document-head-management
198
+ */
190
199
  export function HeadContent() {
191
200
  const tags = useTags()
192
201
  const router = useRouter()
package/src/Matches.tsx CHANGED
@@ -41,6 +41,10 @@ declare module '@tanstack/router-core' {
41
41
  }
42
42
  }
43
43
 
44
+ /**
45
+ * Internal component that renders the router's active match tree with
46
+ * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.
47
+ */
44
48
  /**
45
49
  * Internal component that renders the router's active match tree with
46
50
  * suspense, error, and not-found boundaries. Rendered by `RouterProvider`.
@@ -259,6 +263,10 @@ export function useMatches<
259
263
  *
260
264
  * @link https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchesHook
261
265
  */
266
+ /**
267
+ * Read the full array of active route matches or select a derived subset
268
+ * from the parent boundary up to (but not including) the current match.
269
+ */
262
270
  export function useParentMatches<
263
271
  TRouter extends AnyRouter = RegisteredRouter,
264
272
  TSelected = unknown,
@@ -281,6 +289,10 @@ export function useParentMatches<
281
289
  } as any)
282
290
  }
283
291
 
292
+ /**
293
+ * Read the array of active route matches that are children of the current
294
+ * match (or selected parent) in the match tree.
295
+ */
284
296
  /**
285
297
  * Read the array of active route matches that are children of the current
286
298
  * match (or selected parent) in the match tree.
@@ -7,6 +7,10 @@ import type {
7
7
  RouterOptions,
8
8
  } from '@tanstack/router-core'
9
9
 
10
+ /**
11
+ * Low-level provider that places the router into React context and optionally
12
+ * updates router options from props. Most apps should use `RouterProvider`.
13
+ */
10
14
  /**
11
15
  * Low-level provider that places the router into React context and optionally
12
16
  * updates router options from props. Most apps should use `RouterProvider`.
@@ -57,6 +61,11 @@ export function RouterContextProvider<
57
61
  *
58
62
  * @link https://tanstack.com/router/latest/docs/framework/react/api/router/createRouterFunction
59
63
  */
64
+ /**
65
+ * Top-level component that renders the active route matches and provides the
66
+ * router to the React tree via context. Accepts the same options as
67
+ * `createRouter` via props to update the router instance.
68
+ */
60
69
  export function RouterProvider<
61
70
  TRouter extends AnyRouter = RegisteredRouter,
62
71
  TDehydrated extends Record<string, any> = Record<string, any>,
@@ -1,5 +1,9 @@
1
1
  import { useRouter } from './useRouter'
2
2
 
3
+ /**
4
+ * Server-only helper to emit a script tag exactly once during SSR.
5
+ * Appends an internal marker to signal hydration completion.
6
+ */
3
7
  export function ScriptOnce({ children }: { children: string }) {
4
8
  const router = useRouter()
5
9
  if (!router.isServer) {
package/src/Scripts.tsx CHANGED
@@ -3,6 +3,10 @@ import { useRouterState } from './useRouterState'
3
3
  import { useRouter } from './useRouter'
4
4
  import type { RouterManagedTag } from '@tanstack/router-core'
5
5
 
6
+ /**
7
+ * Render body script tags collected from route matches and SSR manifests.
8
+ * Should be placed near the end of the document body.
9
+ */
6
10
  /**
7
11
  * Render body script tags collected from route matches and SSR manifests.
8
12
  * Should be placed near the end of the document body.