@tanstack/react-router 1.133.25 → 1.133.28
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.
- package/dist/cjs/ClientOnly.cjs.map +1 -1
- package/dist/cjs/ClientOnly.d.cts +5 -0
- package/dist/cjs/HeadContent.cjs.map +1 -1
- package/dist/cjs/HeadContent.d.cts +9 -0
- package/dist/cjs/Matches.cjs.map +1 -1
- package/dist/cjs/Matches.d.cts +12 -0
- package/dist/cjs/RouterProvider.cjs.map +1 -1
- package/dist/cjs/RouterProvider.d.cts +9 -0
- package/dist/cjs/ScriptOnce.cjs.map +1 -1
- package/dist/cjs/ScriptOnce.d.cts +4 -0
- package/dist/cjs/Scripts.cjs.map +1 -1
- package/dist/cjs/Scripts.d.cts +4 -0
- package/dist/cjs/awaited.cjs.map +1 -1
- package/dist/cjs/awaited.d.cts +5 -0
- package/dist/cjs/fileRoute.cjs.map +1 -1
- package/dist/cjs/fileRoute.d.cts +23 -0
- package/dist/cjs/link.cjs.map +1 -1
- package/dist/cjs/link.d.cts +14 -0
- package/dist/cjs/router.cjs.map +1 -1
- package/dist/cjs/router.d.cts +5 -0
- package/dist/cjs/useLoaderData.cjs.map +1 -1
- package/dist/cjs/useLoaderData.d.cts +4 -0
- package/dist/cjs/useLoaderDeps.cjs.map +1 -1
- package/dist/cjs/useLoaderDeps.d.cts +4 -0
- package/dist/cjs/useLocation.cjs.map +1 -1
- package/dist/cjs/useLocation.d.cts +5 -0
- package/dist/cjs/useMatch.cjs.map +1 -1
- package/dist/cjs/useMatch.d.cts +0 -8
- package/dist/cjs/useParams.cjs.map +1 -1
- package/dist/cjs/useParams.d.cts +4 -0
- package/dist/cjs/useRouter.cjs.map +1 -1
- package/dist/cjs/useRouter.d.cts +5 -0
- package/dist/cjs/useRouterState.cjs.map +1 -1
- package/dist/cjs/useRouterState.d.cts +5 -0
- package/dist/cjs/useSearch.cjs.map +1 -1
- package/dist/cjs/useSearch.d.cts +4 -0
- package/dist/esm/ClientOnly.d.ts +5 -0
- package/dist/esm/ClientOnly.js.map +1 -1
- package/dist/esm/HeadContent.d.ts +9 -0
- package/dist/esm/HeadContent.js.map +1 -1
- package/dist/esm/Matches.d.ts +12 -0
- package/dist/esm/Matches.js.map +1 -1
- package/dist/esm/RouterProvider.d.ts +9 -0
- package/dist/esm/RouterProvider.js.map +1 -1
- package/dist/esm/ScriptOnce.d.ts +4 -0
- package/dist/esm/ScriptOnce.js.map +1 -1
- package/dist/esm/Scripts.d.ts +4 -0
- package/dist/esm/Scripts.js.map +1 -1
- package/dist/esm/awaited.d.ts +5 -0
- package/dist/esm/awaited.js.map +1 -1
- package/dist/esm/fileRoute.d.ts +23 -0
- package/dist/esm/fileRoute.js.map +1 -1
- package/dist/esm/link.d.ts +14 -0
- package/dist/esm/link.js.map +1 -1
- package/dist/esm/router.d.ts +5 -0
- package/dist/esm/router.js.map +1 -1
- package/dist/esm/useLoaderData.d.ts +4 -0
- package/dist/esm/useLoaderData.js.map +1 -1
- package/dist/esm/useLoaderDeps.d.ts +4 -0
- package/dist/esm/useLoaderDeps.js.map +1 -1
- package/dist/esm/useLocation.d.ts +5 -0
- package/dist/esm/useLocation.js.map +1 -1
- package/dist/esm/useMatch.d.ts +0 -8
- package/dist/esm/useMatch.js.map +1 -1
- package/dist/esm/useParams.d.ts +4 -0
- package/dist/esm/useParams.js.map +1 -1
- package/dist/esm/useRouter.d.ts +5 -0
- package/dist/esm/useRouter.js.map +1 -1
- package/dist/esm/useRouterState.d.ts +5 -0
- package/dist/esm/useRouterState.js.map +1 -1
- package/dist/esm/useSearch.d.ts +4 -0
- package/dist/esm/useSearch.js.map +1 -1
- package/dist/llms/rules/installation.d.ts +1 -1
- package/dist/llms/rules/installation.js +1 -1
- package/dist/llms/rules/routing.d.ts +1 -1
- package/dist/llms/rules/routing.js +36 -0
- package/dist/llms/rules/setup-and-architecture.d.ts +1 -1
- package/dist/llms/rules/setup-and-architecture.js +7 -7
- package/package.json +3 -3
- package/src/ClientOnly.tsx +8 -0
- package/src/HeadContent.tsx +9 -0
- package/src/Matches.tsx +12 -0
- package/src/RouterProvider.tsx +9 -0
- package/src/ScriptOnce.tsx +4 -0
- package/src/Scripts.tsx +4 -0
- package/src/awaited.tsx +5 -0
- package/src/fileRoute.ts +23 -0
- package/src/link.tsx +15 -0
- package/src/router.ts +5 -0
- package/src/useLoaderData.tsx +4 -0
- package/src/useLoaderDeps.tsx +4 -0
- package/src/useLocation.tsx +5 -0
- package/src/useMatch.tsx +0 -8
- package/src/useParams.tsx +4 -0
- package/src/useRouter.tsx +5 -0
- package/src/useRouterState.tsx +5 -0
- package/src/useSearch.tsx +4 -0
|
@@ -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#
|
|
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: "# Code-Based Routing\n\n> [!TIP]\n> Code-based routing is not recommended for most applications. It is recommended to use [File-Based Routing](../file-based-routing.md) instead.\n\n## \u26A0\uFE0F Before You Start\n\n- If you're using [File-Based Routing](../file-based-routing.md), **skip this guide**.\n- If you still insist on using code-based routing, you must read the [Routing Concepts](../routing-concepts.md) guide first, as it also covers core concepts of the router.\n\n## Route Trees\n\nCode-based routing is no different from file-based routing in that it uses the same route tree concept to organize, match and compose matching routes into a component tree. The only difference is that instead of using the filesystem to organize your routes, you use code.\n\nLet's consider the same route tree from the [Route Trees & Nesting](../route-trees.md#route-trees) guide, and convert it to code-based routing:\n\nHere is the file-based version:\n\n```\nroutes/\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 about.tsx\n\u251C\u2500\u2500 posts/\n\u2502 \u251C\u2500\u2500 index.tsx\n\u2502 \u251C\u2500\u2500 $postId.tsx\n\u251C\u2500\u2500 posts.$postId.edit.tsx\n\u251C\u2500\u2500 settings/\n\u2502 \u251C\u2500\u2500 profile.tsx\n\u2502 \u251C\u2500\u2500 notifications.tsx\n\u251C\u2500\u2500 _pathlessLayout.tsx\n\u251C\u2500\u2500 _pathlessLayout/\n\u2502 \u251C\u2500\u2500 route-a.tsx\n\u251C\u2500\u2500 \u251C\u2500\u2500 route-b.tsx\n\u251C\u2500\u2500 files/\n\u2502 \u251C\u2500\u2500 $.tsx\n```\n\nAnd here is a summarized code-based version:\n\n```tsx\nimport { createRootRoute, createRoute } from '@tanstack/react-router'\n\nconst rootRoute = createRootRoute()\n\nconst indexRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n})\n\nconst aboutRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'about',\n})\n\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n})\n\nconst postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n\nconst postRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '$postId',\n})\n\nconst postEditorRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts/$postId/edit',\n})\n\nconst settingsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'settings',\n})\n\nconst profileRoute = createRoute({\n getParentRoute: () => settingsRoute,\n path: 'profile',\n})\n\nconst notificationsRoute = createRoute({\n getParentRoute: () => settingsRoute,\n path: 'notifications',\n})\n\nconst pathlessLayoutRoute = createRoute({\n getParentRoute: () => rootRoute,\n id: 'pathlessLayout',\n})\n\nconst pathlessLayoutARoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-a',\n})\n\nconst pathlessLayoutBRoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-b',\n})\n\nconst filesRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'files/$',\n})\n```\n\n## Anatomy of a Route\n\nAll other routes other than the root route are configured using the `createRoute` function:\n\n```tsx\nconst route = createRoute({\n getParentRoute: () => rootRoute,\n path: '/posts',\n component: PostsComponent,\n})\n```\n\nThe `getParentRoute` option is a function that returns the parent route of the route you're creating.\n\n**\u2753\u2753\u2753 \"Wait, you're making me pass the parent route for every route I make?\"**\n\nAbsolutely! The reason for passing the parent route has **everything to do with the magical type safety** of TanStack Router. Without the parent route, TypeScript would have no idea what types to supply your route with!\n\n> [!IMPORTANT]\n> For every route that's **NOT** the **Root Route** or a **Pathless Layout Route**, a `path` option is required. This is the path that will be matched against the URL pathname to determine if the route is a match.\n\nWhen configuring route `path` option on a route, it ignores leading and trailing slashes (this does not include \"index\" route paths `/`). You can include them if you want, but they will be normalized internally by TanStack Router. Here is a table of valid paths and what they will be normalized to:\n\n| Path | Normalized Path |\n| -------- | --------------- |\n| `/` | `/` |\n| `/about` | `about` |\n| `about/` | `about` |\n| `about` | `about` |\n| `$` | `$` |\n| `/$` | `$` |\n| `/$/` | `$` |\n\n## Manually building the route tree\n\nWhen building a route tree in code, it's not enough to define the parent route of each route. You must also construct the final route tree by adding each route to its parent route's `children` array. This is because the route tree is not built automatically for you like it is in file-based routing.\n\n```tsx\n/* prettier-ignore */\nconst routeTree = rootRoute.addChildren([\n indexRoute,\n aboutRoute,\n postsRoute.addChildren([\n postsIndexRoute,\n postRoute,\n ]),\n postEditorRoute,\n settingsRoute.addChildren([\n profileRoute,\n notificationsRoute,\n ]),\n pathlessLayoutRoute.addChildren([\n pathlessLayoutARoute,\n pathlessLayoutBRoute,\n ]),\n filesRoute.addChildren([\n fileRoute,\n ]),\n])\n/* prettier-ignore-end */\n```\n\nBut before you can go ahead and build the route tree, you need to understand how the Routing Concepts for Code-Based Routing work.\n\n## Routing Concepts for Code-Based Routing\n\nBelieve it or not, file-based routing is really a superset of code-based routing and uses the filesystem and a bit of code-generation abstraction on top of it to generate this structure you see above automatically.\n\nWe're going to assume you've read the [Routing Concepts](../routing-concepts.md) guide and are familiar with each of these main concepts:\n\n- The Root Route\n- Basic Routes\n- Index Routes\n- Dynamic Route Segments\n- Splat / Catch-All Routes\n- Layout Routes\n- Pathless Routes\n- Non-Nested Routes\n\nNow, let's take a look at how to create each of these route types in code.\n\n## The Root Route\n\nCreating a root route in code-based routing is thankfully the same as doing so in file-based routing. Call the `createRootRoute()` function.\n\nUnlike file-based routing however, you do not need to export the root route if you don't want to. It's certainly not recommended to build an entire route tree and application in a single file (although you can and we do this in the examples to demonstrate routing concepts in brevity).\n\n```tsx\n// Standard root route\nimport { createRootRoute } from '@tanstack/react-router'\n\nconst rootRoute = createRootRoute()\n\n// Root route with Context\nimport { createRootRouteWithContext } from '@tanstack/react-router'\nimport type { QueryClient } from '@tanstack/react-query'\n\nexport interface MyRouterContext {\n queryClient: QueryClient\n}\nconst rootRoute = createRootRouteWithContext<MyRouterContext>()\n```\n\nTo learn more about Context in TanStack Router, see the [Router Context](../../guide/router-context.md) guide.\n\n## Basic Routes\n\nTo create a basic route, simply provide a normal `path` string to the `createRoute` function:\n\n```tsx\nconst aboutRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'about',\n})\n```\n\nSee, it's that simple! The `aboutRoute` will match the URL `/about`.\n\n## Index Routes\n\nUnlike file-based routing, which uses the `index` filename to denote an index route, code-based routing uses a single slash `/` to denote an index route. For example, the `posts.index.tsx` file from our example route tree above would be represented in code-based routing like this:\n\n```tsx\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n})\n\nconst postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n // Notice the single slash `/` here\n path: '/',\n})\n```\n\nSo, the `postsIndexRoute` will match the URL `/posts/` (or `/posts`).\n\n## Dynamic Route Segments\n\nDynamic route segments work exactly the same in code-based routing as they do in file-based routing. Simply prefix a segment of the path with a `$` and it will be captured into the `params` object of the route's `loader` or `component`:\n\n```tsx\nconst postIdRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '$postId',\n // In a loader\n loader: ({ params }) => fetchPost(params.postId),\n // Or in a component\n component: PostComponent,\n})\n\nfunction PostComponent() {\n const { postId } = postIdRoute.useParams()\n return <div>Post ID: {postId}</div>\n}\n```\n\n> [!TIP]\n> If your component is code-split, you can use the [getRouteApi function](../../guide/code-splitting.md#manually-accessing-route-apis-in-other-files-with-the-getrouteapi-helper) to avoid having to import the `postIdRoute` configuration to get access to the typed `useParams()` hook.\n\n## Splat / Catch-All Routes\n\nAs expected, splat/catch-all routes also work the same in code-based routing as they do in file-based routing. Simply prefix a segment of the path with a `$` and it will be captured into the `params` object under the `_splat` key:\n\n```tsx\nconst filesRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'files',\n})\n\nconst fileRoute = createRoute({\n getParentRoute: () => filesRoute,\n path: '$',\n})\n```\n\nFor the URL `/documents/hello-world`, the `params` object will look like this:\n\n```js\n{\n '_splat': 'documents/hello-world'\n}\n```\n\n## Layout Routes\n\nLayout routes are routes that wrap their children in a layout component. In code-based routing, you can create a layout route by simply nesting a route under another route:\n\n```tsx\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n component: PostsLayoutComponent, // The layout component\n})\n\nfunction PostsLayoutComponent() {\n return (\n <div>\n <h1>Posts</h1>\n <Outlet />\n </div>\n )\n}\n\nconst postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n\nconst postsCreateRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: 'create',\n})\n\nconst routeTree = rootRoute.addChildren([\n // The postsRoute is the layout route\n // Its children will be nested under the PostsLayoutComponent\n postsRoute.addChildren([postsIndexRoute, postsCreateRoute]),\n])\n```\n\nNow, both the `postsIndexRoute` and `postsCreateRoute` will render their contents inside of the `PostsLayoutComponent`:\n\n```tsx\n// URL: /posts\n<PostsLayoutComponent>\n <PostsIndexComponent />\n</PostsLayoutComponent>\n\n// URL: /posts/create\n<PostsLayoutComponent>\n <PostsCreateComponent />\n</PostsLayoutComponent>\n```\n\n## Pathless Layout Routes\n\nIn file-based routing a pathless layout route is prefixed with a `_`, but in code-based routing, this is simply a route with an `id` instead of a `path` option. This is because code-based routing does not use the filesystem to organize routes, so there is no need to prefix a route with a `_` to denote that it has no path.\n\n```tsx\nconst pathlessLayoutRoute = createRoute({\n getParentRoute: () => rootRoute,\n id: 'pathlessLayout',\n component: PathlessLayoutComponent,\n})\n\nfunction PathlessLayoutComponent() {\n return (\n <div>\n <h1>Pathless Layout</h1>\n <Outlet />\n </div>\n )\n}\n\nconst pathlessLayoutARoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-a',\n})\n\nconst pathlessLayoutBRoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-b',\n})\n\nconst routeTree = rootRoute.addChildren([\n // The pathless layout route has no path, only an id\n // So its children will be nested under the pathless layout route\n pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]),\n])\n```\n\nNow both `/route-a` and `/route-b` will render their contents inside of the `PathlessLayoutComponent`:\n\n```tsx\n// URL: /route-a\n<PathlessLayoutComponent>\n <RouteAComponent />\n</PathlessLayoutComponent>\n\n// URL: /route-b\n<PathlessLayoutComponent>\n <RouteBComponent />\n</PathlessLayoutComponent>\n```\n\n## Non-Nested Routes\n\nBuilding non-nested routes in code-based routing does not require using a trailing `_` in the path, but does require you to build your route and route tree with the right paths and nesting. Let's consider the route tree where we want the post editor to **not** be nested under the posts route:\n\n- `/posts_/$postId/edit`\n- `/posts`\n - `$postId`\n\nTo do this we need to build a separate route for the post editor and include the entire path in the `path` option from the root of where we want the route to be nested (in this case, the root):\n\n```tsx\n// The posts editor route is nested under the root route\nconst postEditorRoute = createRoute({\n getParentRoute: () => rootRoute,\n // The path includes the entire path we need to match\n path: 'posts/$postId/edit',\n})\n\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n})\n\nconst postRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '$postId',\n})\n\nconst routeTree = rootRoute.addChildren([\n // The post editor route is nested under the root route\n postEditorRoute,\n postsRoute.addChildren([postRoute]),\n])\n```\n\n# File-Based Routing\n\nMost of the TanStack Router documentation is written for file-based routing and is intended to help you understand in more detail how to configure file-based routing and the technical details behind how it works. While file-based routing is the preferred and recommended way to configure TanStack Router, you can also use [code-based routing](../code-based-routing.md) if you prefer.\n\n## What is File-Based Routing?\n\nFile-based routing is a way to configure your routes using the filesystem. Instead of defining your route structure via code, you can define your routes using a series of files and directories that represent the route hierarchy of your application. This brings a number of benefits:\n\n- **Simplicity**: File-based routing is visually intuitive and easy to understand for both new and experienced developers.\n- **Organization**: Routes are organized in a way that mirrors the URL structure of your application.\n- **Scalability**: As your application grows, file-based routing makes it easy to add new routes and maintain existing ones.\n- **Code-Splitting**: File-based routing allows TanStack Router to automatically code-split your routes for better performance.\n- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating managing type linkages for your routes, which can otherwise be a tedious process via code-based routing.\n- **Consistency**: File-based routing enforces a consistent structure for your routes, making it easier to maintain and update your application and move from one project to another.\n\n## `/`s or `.`s?\n\nWhile directories have long been used to represent route hierarchy, file-based routing introduces an additional concept of using the `.` character in the file-name to denote a route nesting. This allows you to avoid creating directories for few deeply nested routes and continue to use directories for wider route hierarchies. Let's take a look at some examples!\n\n## Directory Routes\n\nDirectories can be used to denote route hierarchy, which can be useful for organizing multiple routes into logical groups and also cutting down on the filename length for large groups of deeply nested routes.\n\nSee the example below:\n\n| Filename | Route Path | Component Output |\n| ----------------------- | ------------------------- | --------------------------------- |\n| \u02A6 `__root.tsx` | | `<Root>` |\n| \u02A6 `index.tsx` | `/` (exact) | `<Root><RootIndex>` |\n| \u02A6 `about.tsx` | `/about` | `<Root><About>` |\n| \u02A6 `posts.tsx` | `/posts` | `<Root><Posts>` |\n| \uD83D\uDCC2 `posts` | | |\n| \u2504 \u02A6 `index.tsx` | `/posts` (exact) | `<Root><Posts><PostsIndex>` |\n| \u2504 \u02A6 `$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n| \uD83D\uDCC2 `posts_` | | |\n| \u2504 \uD83D\uDCC2 `$postId` | | |\n| \u2504 \u2504 \u02A6 `edit.tsx` | `/posts/$postId/edit` | `<Root><EditPost>` |\n| \u02A6 `settings.tsx` | `/settings` | `<Root><Settings>` |\n| \uD83D\uDCC2 `settings` | | `<Root><Settings>` |\n| \u2504 \u02A6 `profile.tsx` | `/settings/profile` | `<Root><Settings><Profile>` |\n| \u2504 \u02A6 `notifications.tsx` | `/settings/notifications` | `<Root><Settings><Notifications>` |\n| \u02A6 `_pathlessLayout.tsx` | | `<Root><PathlessLayout>` |\n| \uD83D\uDCC2 `_pathlessLayout` | | |\n| \u2504 \u02A6 `route-a.tsx` | `/route-a` | `<Root><PathlessLayout><RouteA>` |\n| \u2504 \u02A6 `route-b.tsx` | `/route-b` | `<Root><PathlessLayout><RouteB>` |\n| \uD83D\uDCC2 `files` | | |\n| \u2504 \u02A6 `$.tsx` | `/files/$` | `<Root><Files>` |\n| \uD83D\uDCC2 `account` | | |\n| \u2504 \u02A6 `route.tsx` | `/account` | `<Root><Account>` |\n| \u2504 \u02A6 `overview.tsx` | `/account/overview` | `<Root><Account><Overview>` |\n\n## Flat Routes\n\nFlat routing gives you the ability to use `.`s to denote route nesting levels.\n\nThis can be useful when you have a large number of uniquely deeply nested routes and want to avoid creating directories for each one:\n\nSee the example below:\n\n| Filename | Route Path | Component Output |\n| ------------------------------- | ------------------------- | --------------------------------- |\n| \u02A6 `__root.tsx` | | `<Root>` |\n| \u02A6 `index.tsx` | `/` (exact) | `<Root><RootIndex>` |\n| \u02A6 `about.tsx` | `/about` | `<Root><About>` |\n| \u02A6 `posts.tsx` | `/posts` | `<Root><Posts>` |\n| \u02A6 `posts.index.tsx` | `/posts` (exact) | `<Root><Posts><PostsIndex>` |\n| \u02A6 `posts.$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n| \u02A6 `posts_.$postId.edit.tsx` | `/posts/$postId/edit` | `<Root><EditPost>` |\n| \u02A6 `settings.tsx` | `/settings` | `<Root><Settings>` |\n| \u02A6 `settings.profile.tsx` | `/settings/profile` | `<Root><Settings><Profile>` |\n| \u02A6 `settings.notifications.tsx` | `/settings/notifications` | `<Root><Settings><Notifications>` |\n| \u02A6 `_pathlessLayout.tsx` | | `<Root><PathlessLayout>` |\n| \u02A6 `_pathlessLayout.route-a.tsx` | `/route-a` | `<Root><PathlessLayout><RouteA>` |\n| \u02A6 `_pathlessLayout.route-b.tsx` | `/route-b` | `<Root><PathlessLayout><RouteB>` |\n| \u02A6 `files.$.tsx` | `/files/$` | `<Root><Files>` |\n| \u02A6 `account.tsx` | `/account` | `<Root><Account>` |\n| \u02A6 `account.overview.tsx` | `/account/overview` | `<Root><Account><Overview>` |\n\n## Mixed Flat and Directory Routes\n\nIt's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense:\n\nSee the example below:\n\n| Filename | Route Path | Component Output |\n| ------------------------------ | ------------------------- | --------------------------------- |\n| \u02A6 `__root.tsx` | | `<Root>` |\n| \u02A6 `index.tsx` | `/` (exact) | `<Root><RootIndex>` |\n| \u02A6 `about.tsx` | `/about` | `<Root><About>` |\n| \u02A6 `posts.tsx` | `/posts` | `<Root><Posts>` |\n| \uD83D\uDCC2 `posts` | | |\n| \u2504 \u02A6 `index.tsx` | `/posts` (exact) | `<Root><Posts><PostsIndex>` |\n| \u2504 \u02A6 `$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n| \u2504 \u02A6 `$postId.edit.tsx` | `/posts/$postId/edit` | `<Root><Posts><Post><EditPost>` |\n| \u02A6 `settings.tsx` | `/settings` | `<Root><Settings>` |\n| \u02A6 `settings.profile.tsx` | `/settings/profile` | `<Root><Settings><Profile>` |\n| \u02A6 `settings.notifications.tsx` | `/settings/notifications` | `<Root><Settings><Notifications>` |\n| \u02A6 `account.tsx` | `/account` | `<Root><Account>` |\n| \u02A6 `account.overview.tsx` | `/account/overview` | `<Root><Account><Overview>` |\n\nBoth flat and directory routes can be mixed together to create a route tree that uses the best of both worlds where it makes sense.\n\n> [!TIP]\n> If you find that the default file-based routing structure doesn't fit your needs, you can always use [Virtual File Routes](../virtual-file-routes.md) to control the source of your routes whilst still getting the awesome performance benefits of file-based routing.\n\n## Getting started with File-Based Routing\n\nTo get started with file-based routing, you'll need to configure your project's bundler to use the TanStack Router Plugin or the TanStack Router CLI.\n\nTo enable file-based routing, you'll need to be using React with a supported bundler. See if your bundler is listed in the configuration guides below.\n\n[//]: # 'SupportedBundlersList'\n\n- [Installation with Vite](../../installation/with-vite)\n- [Installation with Rspack/Rsbuild](../../installation/with-rspack)\n- [Installation with Webpack](../../installation/with-webpack)\n- [Installation with Esbuild](../../installation/with-esbuild)\n\n[//]: # 'SupportedBundlersList'\n\nWhen using TanStack Router's file-based routing through one of the supported bundlers, our plugin will **automatically generate your route configuration through your bundler's dev and build processes**. It is the easiest way to use TanStack Router's route generation features.\n\nIf your bundler is not yet supported, you can reach out to us on Discord or GitHub to let us know.\n\n# File Naming Conventions\n\nFile-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees & Nesting](../route-trees.md) guide.\n\n| Feature | Description |\n| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **`__root.tsx`** | The root route file must be named `__root.tsx` and must be placed in the root of the configured `routesDirectory`. |\n| **`.` Separator** | Routes can use the `.` character to denote a nested route. For example, `blog.post` will be generated as a child of `blog`. |\n| **`$` Token** | Route segments with the `$` token are parameterized and will extract the value from the URL pathname as a route `param`. |\n| **`_` Prefix** | Route segments with the `_` prefix are considered to be pathless layout routes and will not be used when matching its child routes against the URL pathname. |\n| **`_` Suffix** | Route segments with the `_` suffix exclude the route from being nested under any parent routes. |\n| **`-` Prefix** | Files and folders with the `-` prefix are excluded from the route tree. They will not be added to the `routeTree.gen.ts` file and can be used to colocate logic in route folders. |\n| **`(folder)` folder name pattern** | A folder that matches this pattern is treated as a **route group**, preventing the folder from being included in the route's URL path. |\n| **`[x]` Escaping** | Square brackets escape special characters in filenames that would otherwise have routing meaning. For example, `script[.]js.tsx` becomes `/script.js` and `api[.]v1.tsx` becomes `/api.v1`. |\n| **`index` Token** | Route segments ending with the `index` token (before any file extensions) will match the parent route when the URL pathname matches the parent route exactly. This can be configured via the `indexToken` configuration option, see [options](../../../../api/file-based-routing.md#indextoken). |\n| **`.route.tsx` File Type** | When using directories to organise routes, the `route` suffix can be used to create a route file at the directory's path. For example, `blog.post.route.tsx` or `blog/post/route.tsx` can be used as the route file for the `/blog/post` route. This can be configured via the `routeToken` configuration option, see [options](../../../../api/file-based-routing.md#routetoken). |\n\n> **\uD83D\uDCA1 Remember:** The file-naming conventions for your project could be affected by what [options](../../../../api/file-based-routing.md) are configured.\n\n## Dynamic Path Params\n\nDynamic path params can be used in both flat and directory routes to create routes that can match a dynamic segment of the URL path. Dynamic path params are denoted by the `$` character in the filename:\n\n| Filename | Route Path | Component Output |\n| --------------------- | ---------------- | --------------------- |\n| ... | ... | ... |\n| \u02A6 `posts.$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n\nWe'll learn more about dynamic path params in the [Path Params](../../guide/path-params.md) guide.\n\n## Pathless Routes\n\nPathless routes wrap child routes with either logic or a component without requiring a URL path. Non-path routes are denoted by the `_` character in the filename:\n\n| Filename | Route Path | Component Output |\n| -------------- | ---------- | ---------------- |\n| \u02A6 `_app.tsx` | | |\n| \u02A6 `_app.a.tsx` | /a | `<Root><App><A>` |\n| \u02A6 `_app.b.tsx` | /b | `<Root><App><B>` |\n\nTo learn more about pathless routes, see the [Routing Concepts - Pathless Routes](../routing-concepts.md#pathless-layout-routes) guide.\n\n# Route Matching\n\nRoute matching follows a consistent and predictable pattern. This guide will explain how route trees are matched.\n\nWhen TanStack Router processes your route tree, all of your routes are automatically sorted to match the most specific routes first. This means that regardless of the order your route tree is defined, routes will always be sorted in this order:\n\n- Index Route\n- Static Routes (most specific to least specific)\n- Dynamic Routes (longest to shortest)\n- Splat/Wildcard Routes\n\nConsider the following pseudo route tree:\n\n```\nRoot\n - blog\n - $postId\n - /\n - new\n - /\n - *\n - about\n - about/us\n```\n\nAfter sorting, this route tree will become:\n\n```\nRoot\n - /\n - about/us\n - about\n - blog\n - /\n - new\n - $postId\n - *\n```\n\nThis final order represents the order in which routes will be matched based on specificity.\n\nUsing that route tree, let's follow the matching process for a few different URLs:\n\n- `/blog`\n ```\n Root\n \u274C /\n \u274C about/us\n \u274C about\n \u23E9 blog\n \u2705 /\n - new\n - $postId\n - *\n ```\n- `/blog/my-post`\n ```\n Root\n \u274C /\n \u274C about/us\n \u274C about\n \u23E9 blog\n \u274C /\n \u274C new\n \u2705 $postId\n - *\n ```\n- `/`\n ```\n Root\n \u2705 /\n - about/us\n - about\n - blog\n - /\n - new\n - $postId\n - *\n ```\n- `/not-a-route`\n ```\n Root\n \u274C /\n \u274C about/us\n \u274C about\n \u274C blog\n - /\n - new\n - $postId\n \u2705 *\n ```\n\n# Route Trees\n\nTanStack Router uses a nested route tree to match up the URL with the correct component tree to render.\n\nTo build a route tree, TanStack Router supports:\n\n- [File-Based Routing](../file-based-routing.md)\n- [Code-Based Routing](../code-based-routing.md)\n\nBoth methods support the exact same core features and functionality, but **file-based routing requires less code for the same or better results**. For this reason, **file-based routing is the preferred and recommended way** to configure TanStack Router. Most of the documentation is written from the perspective of file-based routing.\n\n## Route Trees\n\nNested routing is a powerful concept that allows you to use a URL to render a nested component tree. For example, given the URL of `/blog/posts/123`, you could create a route hierarchy that looks like this:\n\n```tsx\n\u251C\u2500\u2500 blog\n\u2502 \u251C\u2500\u2500 posts\n\u2502 \u2502 \u251C\u2500\u2500 $postId\n```\n\nAnd render a component tree that looks like this:\n\n```tsx\n<Blog>\n <Posts>\n <Post postId=\"123\" />\n </Posts>\n</Blog>\n```\n\nLet's take that concept and expand it out to a larger site structure, but with file-names now:\n\n```\n/routes\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 about.tsx\n\u251C\u2500\u2500 posts/\n\u2502 \u251C\u2500\u2500 index.tsx\n\u2502 \u251C\u2500\u2500 $postId.tsx\n\u251C\u2500\u2500 posts.$postId.edit.tsx\n\u251C\u2500\u2500 settings/\n\u2502 \u251C\u2500\u2500 profile.tsx\n\u2502 \u251C\u2500\u2500 notifications.tsx\n\u251C\u2500\u2500 _pathlessLayout/\n\u2502 \u251C\u2500\u2500 route-a.tsx\n\u251C\u2500\u2500 \u251C\u2500\u2500 route-b.tsx\n\u251C\u2500\u2500 files/\n\u2502 \u251C\u2500\u2500 $.tsx\n```\n\nThe above is a valid route tree configuration that can be used with TanStack Router! There's a lot of power and convention to unpack with file-based routing, so let's break it down a bit.\n\n## Route Tree Configuration\n\nRoute trees can be configured using a few different ways:\n\n- [Flat Routes](../file-based-routing.md#flat-routes)\n- [Directories](../file-based-routing.md#directory-routes)\n- [Mixed Flat Routes and Directories](../file-based-routing.md#mixed-flat-and-directory-routes)\n- [Virtual File Routes](../virtual-file-routes.md)\n- [Code-Based Routes](../code-based-routing.md)\n\nPlease be sure to check out the full documentation links above for each type of route tree, or just proceed to the next section to get started with file-based routing.\n\n# Routing Concepts\n\nTanStack Router supports a number of powerful routing concepts that allow you to build complex and dynamic routing systems with ease.\n\nEach of these concepts is useful and powerful, and we'll dive into each of them in the following sections.\n\n## Anatomy of a Route\n\nAll other routes, other than the [Root Route](#the-root-route), are configured using the `createFileRoute` function, which provides type safety when using file-based routing:\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: PostsComponent,\n})\n```\n\nThe `createFileRoute` function takes a single argument, the file-route's path as a string.\n\n**\u2753\u2753\u2753 \"Wait, you're making me pass the path of the route file to `createFileRoute`?\"**\n\nYes! But don't worry, this path is **automatically written and managed by the router for you via the TanStack Router Bundler Plugin or Router CLI.** So, as you create new routes, move routes around or rename routes, the path will be updated for you automatically.\n\nThe reason for this pathname has everything to do with the magical type safety of TanStack Router. Without this pathname, TypeScript would have no idea what file we're in! (We wish TypeScript had a built-in for this, but they don't yet \uD83E\uDD37\u200D\u2642\uFE0F)\n\n## The Root Route\n\nThe root route is the top-most route in the entire tree and encapsulates all other routes as children.\n\n- It has no path\n- It is **always** matched\n- Its `component` is **always** rendered\n\nEven though it doesn't have a path, the root route has access to all of the same functionality as other routes including:\n\n- components\n- loaders\n- search param validation\n- etc.\n\nTo create a root route, call the `createRootRoute()` function and export it as the `Route` variable in your route file:\n\n```tsx\n// Standard root route\nimport { createRootRoute } from '@tanstack/react-router'\n\nexport const Route = createRootRoute()\n\n// Root route with Context\nimport { createRootRouteWithContext } from '@tanstack/react-router'\nimport type { QueryClient } from '@tanstack/react-query'\n\nexport interface MyRouterContext {\n queryClient: QueryClient\n}\nexport const Route = createRootRouteWithContext<MyRouterContext>()\n```\n\nTo learn more about Context in TanStack Router, see the [Router Context](../../guide/router-context.md) guide.\n\n## Basic Routes\n\nBasic routes match a specific path, for example `/about`, `/settings`, `/settings/notifications` are all basic routes, as they match the path exactly.\n\nLet's take a look at an `/about` route:\n\n```tsx\n// about.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/about')({\n component: AboutComponent,\n})\n\nfunction AboutComponent() {\n return <div>About</div>\n}\n```\n\nBasic routes are simple and straightforward. They match the path exactly and render the provided component.\n\n## Index Routes\n\nIndex routes specifically target their parent route when it is **matched exactly and no child route is matched**.\n\nLet's take a look at an index route for a `/posts` URL:\n\n```tsx\n// posts.index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\n// Note the trailing slash, which is used to target index routes\nexport const Route = createFileRoute('/posts/')({\n component: PostsIndexComponent,\n})\n\nfunction PostsIndexComponent() {\n return <div>Please select a post!</div>\n}\n```\n\nThis route will be matched when the URL is `/posts` exactly.\n\n## Dynamic Route Segments\n\nRoute path segments that start with a `$` followed by a label are dynamic and capture that section of the URL into the `params` object for use in your application. For example, a pathname of `/posts/123` would match the `/posts/$postId` route, and the `params` object would be `{ postId: '123' }`.\n\nThese params are then usable in your route's configuration and components! Let's look at a `posts.$postId.tsx` route:\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/$postId')({\n // In a loader\n loader: ({ params }) => fetchPost(params.postId),\n // Or in a component\n component: PostComponent,\n})\n\nfunction PostComponent() {\n // In a component!\n const { postId } = Route.useParams()\n return <div>Post ID: {postId}</div>\n}\n```\n\n> \uD83E\uDDE0 Dynamic segments work at **each** segment of the path. For example, you could have a route with the path of `/posts/$postId/$revisionId` and each `$` segment would be captured into the `params` object.\n\n## Splat / Catch-All Routes\n\nA route with a path of only `$` is called a \"splat\" route because it _always_ captures _any_ remaining section of the URL pathname from the `$` to the end. The captured pathname is then available in the `params` object under the special `_splat` property.\n\nFor example, a route targeting the `files/$` path is a splat route. If the URL pathname is `/files/documents/hello-world`, the `params` object would contain `documents/hello-world` under the special `_splat` property:\n\n```js\n{\n '_splat': 'documents/hello-world'\n}\n```\n\n> \u26A0\uFE0F In v1 of the router, splat routes are also denoted with a `*` instead of a `_splat` key for backwards compatibility. This will be removed in v2.\n\n> \uD83E\uDDE0 Why use `$`? Thanks to tools like Remix, we know that despite `*`s being the most common character to represent a wildcard, they do not play nice with filenames or CLI tools, so just like them, we decided to use `$` instead.\n\n## Optional Path Parameters\n\nOptional path parameters allow you to define route segments that may or may not be present in the URL. They use the `{-$paramName}` syntax and provide flexible routing patterns where certain parameters are optional.\n\n```tsx\n// posts.{-$category}.tsx - Optional category parameter\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/{-$category}')({\n component: PostsComponent,\n})\n\nfunction PostsComponent() {\n const { category } = Route.useParams()\n\n return <div>{category ? `Posts in ${category}` : 'All Posts'}</div>\n}\n```\n\nThis route will match both `/posts` (category is `undefined`) and `/posts/tech` (category is `\"tech\"`).\n\nYou can also define multiple optional parameters in a single route:\n\n```tsx\n// posts.{-$category}.{-$slug}.tsx\nexport const Route = createFileRoute('/posts/{-$category}/{-$slug}')({\n component: PostsComponent,\n})\n```\n\nThis route matches `/posts`, `/posts/tech`, and `/posts/tech/hello-world`.\n\n> \uD83E\uDDE0 Routes with optional parameters are ranked lower in priority than exact matches, ensuring that more specific routes like `/posts/featured` are matched before `/posts/{-$category}`.\n\n## Layout Routes\n\nLayout routes are used to wrap child routes with additional components and logic. They are useful for:\n\n- Wrapping child routes with a layout component\n- Enforcing a `loader` requirement before displaying any child routes\n- Validating and providing search params to child routes\n- Providing fallbacks for error components or pending elements to child routes\n- Providing shared context to all child routes\n- And more!\n\nLet's take a look at an example layout route called `app.tsx`:\n\n```\nroutes/\n\u251C\u2500\u2500 app.tsx\n\u251C\u2500\u2500 app.dashboard.tsx\n\u251C\u2500\u2500 app.settings.tsx\n```\n\nIn the tree above, `app.tsx` is a layout route that wraps two child routes, `app.dashboard.tsx` and `app.settings.tsx`.\n\nThis tree structure is used to wrap the child routes with a layout component:\n\n```tsx\nimport { Outlet, createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/app')({\n component: AppLayoutComponent,\n})\n\nfunction AppLayoutComponent() {\n return (\n <div>\n <h1>App Layout</h1>\n <Outlet />\n </div>\n )\n}\n```\n\nThe following table shows which component(s) will be rendered based on the URL:\n\n| URL Path | Component |\n| ---------------- | ------------------------ |\n| `/app` | `<AppLayout>` |\n| `/app/dashboard` | `<AppLayout><Dashboard>` |\n| `/app/settings` | `<AppLayout><Settings>` |\n\nSince TanStack Router supports mixed flat and directory routes, you can also express your application's routing using layout routes within directories:\n\n```\nroutes/\n\u251C\u2500\u2500 app/\n\u2502 \u251C\u2500\u2500 route.tsx\n\u2502 \u251C\u2500\u2500 dashboard.tsx\n\u2502 \u251C\u2500\u2500 settings.tsx\n```\n\nIn this nested tree, the `app/route.tsx` file is a configuration for the layout route that wraps two child routes, `app/dashboard.tsx` and `app/settings.tsx`.\n\nLayout Routes also let you enforce component and loader logic for Dynamic Route Segments:\n\n```\nroutes/\n\u251C\u2500\u2500 app/users/\n\u2502 \u251C\u2500\u2500 $userId/\n| | \u251C\u2500\u2500 route.tsx\n| | \u251C\u2500\u2500 index.tsx\n| | \u251C\u2500\u2500 edit.tsx\n```\n\n## Pathless Layout Routes\n\nLike [Layout Routes](#layout-routes), Pathless Layout Routes are used to wrap child routes with additional components and logic. However, pathless layout routes do not require a matching `path` in the URL and are used to wrap child routes with additional components and logic without requiring a matching `path` in the URL.\n\nPathless Layout Routes are prefixed with an underscore (`_`) to denote that they are \"pathless\".\n\n> \uD83E\uDDE0 The part of the path after the `_` prefix is used as the route's ID and is required because every route must be uniquely identifiable, especially when using TypeScript so as to avoid type errors and accomplish autocomplete effectively.\n\nLet's take a look at an example route called `_pathlessLayout.tsx`:\n\n```\n\nroutes/\n\u251C\u2500\u2500 _pathlessLayout.tsx\n\u251C\u2500\u2500 _pathlessLayout.a.tsx\n\u251C\u2500\u2500 _pathlessLayout.b.tsx\n\n```\n\nIn the tree above, `_pathlessLayout.tsx` is a pathless layout route that wraps two child routes, `_pathlessLayout.a.tsx` and `_pathlessLayout.b.tsx`.\n\nThe `_pathlessLayout.tsx` route is used to wrap the child routes with a Pathless layout component:\n\n```tsx\nimport { Outlet, createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/_pathlessLayout')({\n component: PathlessLayoutComponent,\n})\n\nfunction PathlessLayoutComponent() {\n return (\n <div>\n <h1>Pathless layout</h1>\n <Outlet />\n </div>\n )\n}\n```\n\nThe following table shows which component will be rendered based on the URL:\n\n| URL Path | Component |\n| -------- | --------------------- |\n| `/` | `<Index>` |\n| `/a` | `<PathlessLayout><A>` |\n| `/b` | `<PathlessLayout><B>` |\n\nSince TanStack Router supports mixed flat and directory routes, you can also express your application's routing using pathless layout routes within directories:\n\n```\nroutes/\n\u251C\u2500\u2500 _pathlessLayout/\n\u2502 \u251C\u2500\u2500 route.tsx\n\u2502 \u251C\u2500\u2500 a.tsx\n\u2502 \u251C\u2500\u2500 b.tsx\n```\n\nHowever, unlike Layout Routes, since Pathless Layout Routes do match based on URL path segments, this means that these routes do not support [Dynamic Route Segments](#dynamic-route-segments) as part of their path and therefore cannot be matched in the URL.\n\nThis means that you cannot do this:\n\n```\nroutes/\n\u251C\u2500\u2500 _$postId/ \u274C\n\u2502 \u251C\u2500\u2500 ...\n```\n\nRather, you'd have to do this:\n\n```\nroutes/\n\u251C\u2500\u2500 $postId/\n\u251C\u2500\u2500 _postPathlessLayout/ \u2705\n\u2502 \u251C\u2500\u2500 ...\n```\n\n## Non-Nested Routes\n\nNon-nested routes can be created by suffixing a parent file route segment with a `_` and are used to **un-nest** a route from its parents and render its own component tree.\n\nConsider the following flat route tree:\n\n```\nroutes/\n\u251C\u2500\u2500 posts.tsx\n\u251C\u2500\u2500 posts.$postId.tsx\n\u251C\u2500\u2500 posts_.$postId.edit.tsx\n```\n\nThe following table shows which component will be rendered based on the URL:\n\n| URL Path | Component |\n| ----------------- | ---------------------------- |\n| `/posts` | `<Posts>` |\n| `/posts/123` | `<Posts><Post postId=\"123\">` |\n| `/posts/123/edit` | `<PostEditor postId=\"123\">` |\n\n- The `posts.$postId.tsx` route is nested as normal under the `posts.tsx` route and will render `<Posts><Post>`.\n- The `posts_.$postId.edit.tsx` route **does not share** the same `posts` prefix as the other routes and therefore will be treated as if it is a top-level route and will render `<PostEditor>`.\n\n## Excluding Files and Folders from Routes\n\nFiles and folders can be excluded from route generation with a `-` prefix attached to the file name. This gives you the ability to colocate logic in the route directories.\n\nConsider the following route tree:\n\n```\nroutes/\n\u251C\u2500\u2500 posts.tsx\n\u251C\u2500\u2500 -posts-table.tsx // \uD83D\uDC48\uD83C\uDFFC ignored\n\u251C\u2500\u2500 -components/ // \uD83D\uDC48\uD83C\uDFFC ignored\n\u2502 \u251C\u2500\u2500 header.tsx // \uD83D\uDC48\uD83C\uDFFC ignored\n\u2502 \u251C\u2500\u2500 footer.tsx // \uD83D\uDC48\uD83C\uDFFC ignored\n\u2502 \u251C\u2500\u2500 ...\n```\n\nWe can import from the excluded files into our posts route\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\nimport { PostsTable } from './-posts-table'\nimport { PostsHeader } from './-components/header'\nimport { PostsFooter } from './-components/footer'\n\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n component: PostComponent,\n})\n\nfunction PostComponent() {\n const posts = Route.useLoaderData()\n\n return (\n <div>\n <PostsHeader />\n <PostsTable posts={posts} />\n <PostsFooter />\n </div>\n )\n}\n```\n\nThe excluded files will not be added to `routeTree.gen.ts`.\n\n## Pathless Route Group Directories\n\nPathless route group directories use `()` as a way to group routes files together regardless of their path. They are purely organizational and do not affect the route tree or component tree in any way.\n\n```\nroutes/\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 (app)/\n\u2502 \u251C\u2500\u2500 dashboard.tsx\n\u2502 \u251C\u2500\u2500 settings.tsx\n\u2502 \u251C\u2500\u2500 users.tsx\n\u251C\u2500\u2500 (auth)/\n\u2502 \u251C\u2500\u2500 login.tsx\n\u2502 \u251C\u2500\u2500 register.tsx\n```\n\nIn the example above, the `app` and `auth` directories are purely organizational and do not affect the route tree or component tree in any way. They are used to group related routes together for easier navigation and organization.\n\nThe following table shows which component will be rendered based on the URL:\n\n| URL Path | Component |\n| ------------ | ------------- |\n| `/` | `<Index>` |\n| `/dashboard` | `<Dashboard>` |\n| `/settings` | `<Settings>` |\n| `/users` | `<Users>` |\n| `/login` | `<Login>` |\n| `/register` | `<Register>` |\n\nAs you can see, the `app` and `auth` directories are purely organizational and do not affect the route tree or component tree in any way.\n\n# Virtual File Routes\n\n> We'd like to thank the Remix team for [pioneering the concept of virtual file routes](https://www.youtube.com/watch?v=fjTX8hQTlEc&t=730s). We've taken inspiration from their work and adapted it to work with TanStack Router's existing file-based route-tree generation.\n\nVirtual file routes are a powerful concept that allows you to build a route tree programmatically using code that references real files in your project. This can be useful if:\n\n- You have an existing route organization that you want to keep.\n- You want to customize the location of your route files.\n- You want to completely override TanStack Router's file-based route generation and build your own convention.\n\nHere's a quick example of using virtual file routes to map a route tree to a set of real files in your project:\n\n```tsx\n// routes.ts\nimport {\n rootRoute,\n route,\n index,\n layout,\n physical,\n} from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n index('index.tsx'),\n layout('pathlessLayout.tsx', [\n route('/dashboard', 'app/dashboard.tsx', [\n index('app/dashboard-index.tsx'),\n route('/invoices', 'app/dashboard-invoices.tsx', [\n index('app/invoices-index.tsx'),\n route('$id', 'app/invoice-detail.tsx'),\n ]),\n ]),\n physical('/posts', 'posts'),\n ]),\n])\n```\n\n## Configuration\n\nVirtual file routes can be configured either via:\n\n- The `TanStackRouter` plugin for Vite/Rspack/Webpack\n- The `tsr.config.json` file for the TanStack Router CLI\n\n## Configuration via the TanStackRouter Plugin\n\nIf you're using the `TanStackRouter` plugin for Vite/Rspack/Webpack, you can configure virtual file routes by passing the path of your routes file to the `virtualRoutesConfig` option when setting up the 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\nexport default defineConfig({\n plugins: [\n tanstackRouter({\n target: 'react',\n virtualRouteConfig: './routes.ts',\n }),\n react(),\n ],\n})\n```\n\nOr, you choose to define the virtual routes directly in the configuration:\n\n```tsx\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\nimport { rootRoute } from '@tanstack/virtual-file-routes'\n\nconst routes = rootRoute('root.tsx', [\n // ... the rest of your virtual route tree\n])\n\nexport default defineConfig({\n plugins: [tanstackRouter({ virtualRouteConfig: routes }), react()],\n})\n```\n\n## Creating Virtual File Routes\n\nTo create virtual file routes, you'll need to import the `@tanstack/virtual-file-routes` package. This package provides a set of functions that allow you to create virtual routes that reference real files in your project. A few utility functions are exported from the package:\n\n- `rootRoute` - Creates a virtual root route.\n- `route` - Creates a virtual route.\n- `index` - Creates a virtual index route.\n- `layout` - Creates a virtual pathless layout route.\n- `physical` - Creates a physical virtual route (more on this later).\n\n## Virtual Root Route\n\nThe `rootRoute` function is used to create a virtual root route. It takes a file name and an array of children routes. Here's an example of a virtual root route:\n\n```tsx\n// routes.ts\nimport { rootRoute } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n // ... children routes\n])\n```\n\n## Virtual Route\n\nThe `route` function is used to create a virtual route. It takes a path, a file name, and an array of children routes. Here's an example of a virtual route:\n\n```tsx\n// routes.ts\nimport { route } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n route('/about', 'about.tsx', [\n // ... children routes\n ]),\n])\n```\n\nYou can also define a virtual route without a file name. This allows to set a common path prefix for its children:\n\n```tsx\n// routes.ts\nimport { route } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n route('/hello', [\n route('/world', 'world.tsx'), // full path will be \"/hello/world\"\n route('/universe', 'universe.tsx'), // full path will be \"/hello/universe\"\n ]),\n])\n```\n\n## Virtual Index Route\n\nThe `index` function is used to create a virtual index route. It takes a file name. Here's an example of a virtual index route:\n\n```tsx\nimport { index } from '@tanstack/virtual-file-routes'\n\nconst routes = rootRoute('root.tsx', [index('index.tsx')])\n```\n\n## Virtual Pathless Route\n\nThe `layout` function is used to create a virtual pathless route. It takes a file name, an array of children routes, and an optional pathless ID. Here's an example of a virtual pathless route:\n\n```tsx\n// routes.ts\nimport { layout } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n layout('pathlessLayout.tsx', [\n // ... children routes\n ]),\n])\n```\n\nYou can also specify a pathless ID to give the route a unique identifier that is different from the filename:\n\n```tsx\n// routes.ts\nimport { layout } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n layout('my-pathless-layout-id', 'pathlessLayout.tsx', [\n // ... children routes\n ]),\n])\n```\n\n## Physical Virtual Routes\n\nPhysical virtual routes are a way to \"mount\" a directory of good ol' TanStack Router File Based routing convention under a specific URL path. This can be useful if you are using virtual routes to customize a small portion of your route tree high up in the hierarchy, but want to use the standard file-based routing convention for sub-routes and directories.\n\nConsider the following file structure:\n\n```\n/routes\n\u251C\u2500\u2500 root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 pathlessLayout.tsx\n\u251C\u2500\u2500 app\n\u2502 \u251C\u2500\u2500 dashboard.tsx\n\u2502 \u251C\u2500\u2500 dashboard-index.tsx\n\u2502 \u251C\u2500\u2500 dashboard-invoices.tsx\n\u2502 \u251C\u2500\u2500 invoices-index.tsx\n\u2502 \u251C\u2500\u2500 invoice-detail.tsx\n\u2514\u2500\u2500 posts\n \u251C\u2500\u2500 index.tsx\n \u251C\u2500\u2500 $postId.tsx\n \u251C\u2500\u2500 $postId.edit.tsx\n \u251C\u2500\u2500 comments/\n \u2502 \u251C\u2500\u2500 index.tsx\n \u2502 \u251C\u2500\u2500 $commentId.tsx\n \u2514\u2500\u2500 likes/\n \u251C\u2500\u2500 index.tsx\n \u251C\u2500\u2500 $likeId.tsx\n```\n\nLet's use virtual routes to customize our route tree for everything but `posts`, then use physical virtual routes to mount the `posts` directory under the `/posts` path:\n\n```tsx\n// routes.ts\nexport const routes = rootRoute('root.tsx', [\n // Set up your virtual routes as normal\n index('index.tsx'),\n layout('pathlessLayout.tsx', [\n route('/dashboard', 'app/dashboard.tsx', [\n index('app/dashboard-index.tsx'),\n route('/invoices', 'app/dashboard-invoices.tsx', [\n index('app/invoices-index.tsx'),\n route('$id', 'app/invoice-detail.tsx'),\n ]),\n ]),\n // Mount the `posts` directory under the `/posts` path\n physical('/posts', 'posts'),\n ]),\n])\n```\n\n## Virtual Routes inside of TanStack Router File Based routing\n\nThe previous section showed you how you can use TanStack Router's File Based routing convention inside of a virtual route configuration.\nHowever, the opposite is possible as well. \nYou can configure the main part of your app's route tree using TanStack Router's File Based routing convention and opt into virtual route configuration for specific subtrees.\n\nConsider the following file structure:\n\n```\n/routes\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 foo\n\u2502 \u251C\u2500\u2500 bar\n\u2502 \u2502 \u251C\u2500\u2500 __virtual.ts\n\u2502 \u2502 \u251C\u2500\u2500 details.tsx\n\u2502 \u2502 \u251C\u2500\u2500 home.tsx\n\u2502 \u2502 \u2514\u2500\u2500 route.ts\n\u2502 \u2514\u2500\u2500 bar.tsx\n\u2514\u2500\u2500 index.tsx\n```\n\nLet's look at the `bar` directory which contains a special file named `__virtual.ts`. This file instructs the generator to switch over to virtual file route configuration for this directory (and its child directories).\n\n`__virtual.ts` configures the virtual routes for that particular subtree of the route tree. It uses the same API as explained above, with the only difference being that no `rootRoute` is defined for that subtree:\n\n```tsx\n// routes/foo/bar/__virtual.ts\nimport {\n defineVirtualSubtreeConfig,\n index,\n route,\n} from '@tanstack/virtual-file-routes'\n\nexport default defineVirtualSubtreeConfig([\n index('home.tsx'),\n route('$id', 'details.tsx'),\n])\n```\n\nThe helper function `defineVirtualSubtreeConfig` is closely modeled after vite's `defineConfig` and allows you to define a subtree configuration via a default export. The default export can either be\n\n- a subtree config object\n- a function returning a subtree config object\n- an async function returning a subtree config object\n\n## Inception\n\nYou can mix and match TanStack Router's File Based routing convention and virtual route configuration however you like. \nLet's go deeper! \nCheck out the following example that starts off using File Based routing convention, switches over to virtual route configuration for `/posts`, switches back to File Based routing convention for `/posts/lets-go` only to switch over to virtual route configuration again for `/posts/lets-go/deeper`.\n\n```\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 posts\n\u2502 \u251C\u2500\u2500 __virtual.ts\n\u2502 \u251C\u2500\u2500 details.tsx\n\u2502 \u251C\u2500\u2500 home.tsx\n\u2502 \u2514\u2500\u2500 lets-go\n\u2502 \u251C\u2500\u2500 deeper\n\u2502 \u2502 \u251C\u2500\u2500 __virtual.ts\n\u2502 \u2502 \u2514\u2500\u2500 home.tsx\n\u2502 \u2514\u2500\u2500 index.tsx\n\u2514\u2500\u2500 posts.tsx\n```\n\n## Configuration via the TanStack Router CLI\n\nIf you're using the TanStack Router CLI, you can configure virtual file routes by defining the path to your routes file in the `tsr.config.json` file:\n\n```json\n// tsr.config.json\n{\n \"virtualRouteConfig\": \"./routes.ts\"\n}\n```\n\nOr you can define the virtual routes directly in the configuration, while much less common allows you to configure them via the TanStack Router CLI by adding a `virtualRouteConfig` object to your `tsr.config.json` file and defining your virtual routes and passing the resulting JSON that is generated by calling the actual `rootRoute`/`route`/`index`/etc functions from the `@tanstack/virtual-file-routes` package:\n\n```json\n// tsr.config.json\n{\n \"virtualRouteConfig\": {\n \"type\": \"root\",\n \"file\": \"root.tsx\",\n \"children\": [\n {\n \"type\": \"index\",\n \"file\": \"home.tsx\"\n },\n {\n \"type\": \"route\",\n \"file\": \"posts/posts.tsx\",\n \"path\": \"/posts\",\n \"children\": [\n {\n \"type\": \"index\",\n \"file\": \"posts/posts-home.tsx\"\n },\n {\n \"type\": \"route\",\n \"file\": \"posts/posts-detail.tsx\",\n \"path\": \"$postId\"\n }\n ]\n },\n {\n \"type\": \"layout\",\n \"id\": \"first\",\n \"file\": \"layout/first-pathless-layout.tsx\",\n \"children\": [\n {\n \"type\": \"layout\",\n \"id\": \"second\",\n \"file\": \"layout/second-pathless-layout.tsx\",\n \"children\": [\n {\n \"type\": \"route\",\n \"file\": \"a.tsx\",\n \"path\": \"/route-a\"\n },\n {\n \"type\": \"route\",\n \"file\": \"b.tsx\",\n \"path\": \"/route-b\"\n }\n ]\n }\n ]\n }\n ]\n }\n}\n```\n\n";
|
|
1
|
+
declare const _default: "# Code-Based Routing\n\n> [!TIP]\n> Code-based routing is not recommended for most applications. It is recommended to use [File-Based Routing](../file-based-routing.md) instead.\n\n## \u26A0\uFE0F Before You Start\n\n- If you're using [File-Based Routing](../file-based-routing.md), **skip this guide**.\n- If you still insist on using code-based routing, you must read the [Routing Concepts](../routing-concepts.md) guide first, as it also covers core concepts of the router.\n\n## Route Trees\n\nCode-based routing is no different from file-based routing in that it uses the same route tree concept to organize, match and compose matching routes into a component tree. The only difference is that instead of using the filesystem to organize your routes, you use code.\n\nLet's consider the same route tree from the [Route Trees & Nesting](../route-trees.md#route-trees) guide, and convert it to code-based routing:\n\nHere is the file-based version:\n\n```\nroutes/\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 about.tsx\n\u251C\u2500\u2500 posts/\n\u2502 \u251C\u2500\u2500 index.tsx\n\u2502 \u251C\u2500\u2500 $postId.tsx\n\u251C\u2500\u2500 posts.$postId.edit.tsx\n\u251C\u2500\u2500 settings/\n\u2502 \u251C\u2500\u2500 profile.tsx\n\u2502 \u251C\u2500\u2500 notifications.tsx\n\u251C\u2500\u2500 _pathlessLayout.tsx\n\u251C\u2500\u2500 _pathlessLayout/\n\u2502 \u251C\u2500\u2500 route-a.tsx\n\u251C\u2500\u2500 \u251C\u2500\u2500 route-b.tsx\n\u251C\u2500\u2500 files/\n\u2502 \u251C\u2500\u2500 $.tsx\n```\n\nAnd here is a summarized code-based version:\n\n```tsx\nimport { createRootRoute, createRoute } from '@tanstack/react-router'\n\nconst rootRoute = createRootRoute()\n\nconst indexRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n})\n\nconst aboutRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'about',\n})\n\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n})\n\nconst postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n\nconst postRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '$postId',\n})\n\nconst postEditorRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts/$postId/edit',\n})\n\nconst settingsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'settings',\n})\n\nconst profileRoute = createRoute({\n getParentRoute: () => settingsRoute,\n path: 'profile',\n})\n\nconst notificationsRoute = createRoute({\n getParentRoute: () => settingsRoute,\n path: 'notifications',\n})\n\nconst pathlessLayoutRoute = createRoute({\n getParentRoute: () => rootRoute,\n id: 'pathlessLayout',\n})\n\nconst pathlessLayoutARoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-a',\n})\n\nconst pathlessLayoutBRoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-b',\n})\n\nconst filesRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'files/$',\n})\n```\n\n## Anatomy of a Route\n\nAll other routes other than the root route are configured using the `createRoute` function:\n\n```tsx\nconst route = createRoute({\n getParentRoute: () => rootRoute,\n path: '/posts',\n component: PostsComponent,\n})\n```\n\nThe `getParentRoute` option is a function that returns the parent route of the route you're creating.\n\n**\u2753\u2753\u2753 \"Wait, you're making me pass the parent route for every route I make?\"**\n\nAbsolutely! The reason for passing the parent route has **everything to do with the magical type safety** of TanStack Router. Without the parent route, TypeScript would have no idea what types to supply your route with!\n\n> [!IMPORTANT]\n> For every route that's **NOT** the **Root Route** or a **Pathless Layout Route**, a `path` option is required. This is the path that will be matched against the URL pathname to determine if the route is a match.\n\nWhen configuring route `path` option on a route, it ignores leading and trailing slashes (this does not include \"index\" route paths `/`). You can include them if you want, but they will be normalized internally by TanStack Router. Here is a table of valid paths and what they will be normalized to:\n\n| Path | Normalized Path |\n| -------- | --------------- |\n| `/` | `/` |\n| `/about` | `about` |\n| `about/` | `about` |\n| `about` | `about` |\n| `$` | `$` |\n| `/$` | `$` |\n| `/$/` | `$` |\n\n## Manually building the route tree\n\nWhen building a route tree in code, it's not enough to define the parent route of each route. You must also construct the final route tree by adding each route to its parent route's `children` array. This is because the route tree is not built automatically for you like it is in file-based routing.\n\n```tsx\n/* prettier-ignore */\nconst routeTree = rootRoute.addChildren([\n indexRoute,\n aboutRoute,\n postsRoute.addChildren([\n postsIndexRoute,\n postRoute,\n ]),\n postEditorRoute,\n settingsRoute.addChildren([\n profileRoute,\n notificationsRoute,\n ]),\n pathlessLayoutRoute.addChildren([\n pathlessLayoutARoute,\n pathlessLayoutBRoute,\n ]),\n filesRoute.addChildren([\n fileRoute,\n ]),\n])\n/* prettier-ignore-end */\n```\n\nBut before you can go ahead and build the route tree, you need to understand how the Routing Concepts for Code-Based Routing work.\n\n## Routing Concepts for Code-Based Routing\n\nBelieve it or not, file-based routing is really a superset of code-based routing and uses the filesystem and a bit of code-generation abstraction on top of it to generate this structure you see above automatically.\n\nWe're going to assume you've read the [Routing Concepts](../routing-concepts.md) guide and are familiar with each of these main concepts:\n\n- The Root Route\n- Basic Routes\n- Index Routes\n- Dynamic Route Segments\n- Splat / Catch-All Routes\n- Layout Routes\n- Pathless Routes\n- Non-Nested Routes\n\nNow, let's take a look at how to create each of these route types in code.\n\n## The Root Route\n\nCreating a root route in code-based routing is thankfully the same as doing so in file-based routing. Call the `createRootRoute()` function.\n\nUnlike file-based routing however, you do not need to export the root route if you don't want to. It's certainly not recommended to build an entire route tree and application in a single file (although you can and we do this in the examples to demonstrate routing concepts in brevity).\n\n```tsx\n// Standard root route\nimport { createRootRoute } from '@tanstack/react-router'\n\nconst rootRoute = createRootRoute()\n\n// Root route with Context\nimport { createRootRouteWithContext } from '@tanstack/react-router'\nimport type { QueryClient } from '@tanstack/react-query'\n\nexport interface MyRouterContext {\n queryClient: QueryClient\n}\nconst rootRoute = createRootRouteWithContext<MyRouterContext>()\n```\n\nTo learn more about Context in TanStack Router, see the [Router Context](../../guide/router-context.md) guide.\n\n## Basic Routes\n\nTo create a basic route, simply provide a normal `path` string to the `createRoute` function:\n\n```tsx\nconst aboutRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'about',\n})\n```\n\nSee, it's that simple! The `aboutRoute` will match the URL `/about`.\n\n## Index Routes\n\nUnlike file-based routing, which uses the `index` filename to denote an index route, code-based routing uses a single slash `/` to denote an index route. For example, the `posts.index.tsx` file from our example route tree above would be represented in code-based routing like this:\n\n```tsx\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n})\n\nconst postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n // Notice the single slash `/` here\n path: '/',\n})\n```\n\nSo, the `postsIndexRoute` will match the URL `/posts/` (or `/posts`).\n\n## Dynamic Route Segments\n\nDynamic route segments work exactly the same in code-based routing as they do in file-based routing. Simply prefix a segment of the path with a `$` and it will be captured into the `params` object of the route's `loader` or `component`:\n\n```tsx\nconst postIdRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '$postId',\n // In a loader\n loader: ({ params }) => fetchPost(params.postId),\n // Or in a component\n component: PostComponent,\n})\n\nfunction PostComponent() {\n const { postId } = postIdRoute.useParams()\n return <div>Post ID: {postId}</div>\n}\n```\n\n> [!TIP]\n> If your component is code-split, you can use the [getRouteApi function](../../guide/code-splitting.md#manually-accessing-route-apis-in-other-files-with-the-getrouteapi-helper) to avoid having to import the `postIdRoute` configuration to get access to the typed `useParams()` hook.\n\n## Splat / Catch-All Routes\n\nAs expected, splat/catch-all routes also work the same in code-based routing as they do in file-based routing. Simply prefix a segment of the path with a `$` and it will be captured into the `params` object under the `_splat` key:\n\n```tsx\nconst filesRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'files',\n})\n\nconst fileRoute = createRoute({\n getParentRoute: () => filesRoute,\n path: '$',\n})\n```\n\nFor the URL `/documents/hello-world`, the `params` object will look like this:\n\n```js\n{\n '_splat': 'documents/hello-world'\n}\n```\n\n## Layout Routes\n\nLayout routes are routes that wrap their children in a layout component. In code-based routing, you can create a layout route by simply nesting a route under another route:\n\n```tsx\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n component: PostsLayoutComponent, // The layout component\n})\n\nfunction PostsLayoutComponent() {\n return (\n <div>\n <h1>Posts</h1>\n <Outlet />\n </div>\n )\n}\n\nconst postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n\nconst postsCreateRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: 'create',\n})\n\nconst routeTree = rootRoute.addChildren([\n // The postsRoute is the layout route\n // Its children will be nested under the PostsLayoutComponent\n postsRoute.addChildren([postsIndexRoute, postsCreateRoute]),\n])\n```\n\nNow, both the `postsIndexRoute` and `postsCreateRoute` will render their contents inside of the `PostsLayoutComponent`:\n\n```tsx\n// URL: /posts\n<PostsLayoutComponent>\n <PostsIndexComponent />\n</PostsLayoutComponent>\n\n// URL: /posts/create\n<PostsLayoutComponent>\n <PostsCreateComponent />\n</PostsLayoutComponent>\n```\n\n## Pathless Layout Routes\n\nIn file-based routing a pathless layout route is prefixed with a `_`, but in code-based routing, this is simply a route with an `id` instead of a `path` option. This is because code-based routing does not use the filesystem to organize routes, so there is no need to prefix a route with a `_` to denote that it has no path.\n\n```tsx\nconst pathlessLayoutRoute = createRoute({\n getParentRoute: () => rootRoute,\n id: 'pathlessLayout',\n component: PathlessLayoutComponent,\n})\n\nfunction PathlessLayoutComponent() {\n return (\n <div>\n <h1>Pathless Layout</h1>\n <Outlet />\n </div>\n )\n}\n\nconst pathlessLayoutARoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-a',\n})\n\nconst pathlessLayoutBRoute = createRoute({\n getParentRoute: () => pathlessLayoutRoute,\n path: 'route-b',\n})\n\nconst routeTree = rootRoute.addChildren([\n // The pathless layout route has no path, only an id\n // So its children will be nested under the pathless layout route\n pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]),\n])\n```\n\nNow both `/route-a` and `/route-b` will render their contents inside of the `PathlessLayoutComponent`:\n\n```tsx\n// URL: /route-a\n<PathlessLayoutComponent>\n <RouteAComponent />\n</PathlessLayoutComponent>\n\n// URL: /route-b\n<PathlessLayoutComponent>\n <RouteBComponent />\n</PathlessLayoutComponent>\n```\n\n## Non-Nested Routes\n\nBuilding non-nested routes in code-based routing does not require using a trailing `_` in the path, but does require you to build your route and route tree with the right paths and nesting. Let's consider the route tree where we want the post editor to **not** be nested under the posts route:\n\n- `/posts_/$postId/edit`\n- `/posts`\n - `$postId`\n\nTo do this we need to build a separate route for the post editor and include the entire path in the `path` option from the root of where we want the route to be nested (in this case, the root):\n\n```tsx\n// The posts editor route is nested under the root route\nconst postEditorRoute = createRoute({\n getParentRoute: () => rootRoute,\n // The path includes the entire path we need to match\n path: 'posts/$postId/edit',\n})\n\nconst postsRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: 'posts',\n})\n\nconst postRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '$postId',\n})\n\nconst routeTree = rootRoute.addChildren([\n // The post editor route is nested under the root route\n postEditorRoute,\n postsRoute.addChildren([postRoute]),\n])\n```\n\n# File-Based Routing\n\nMost of the TanStack Router documentation is written for file-based routing and is intended to help you understand in more detail how to configure file-based routing and the technical details behind how it works. While file-based routing is the preferred and recommended way to configure TanStack Router, you can also use [code-based routing](../code-based-routing.md) if you prefer.\n\n## What is File-Based Routing?\n\nFile-based routing is a way to configure your routes using the filesystem. Instead of defining your route structure via code, you can define your routes using a series of files and directories that represent the route hierarchy of your application. This brings a number of benefits:\n\n- **Simplicity**: File-based routing is visually intuitive and easy to understand for both new and experienced developers.\n- **Organization**: Routes are organized in a way that mirrors the URL structure of your application.\n- **Scalability**: As your application grows, file-based routing makes it easy to add new routes and maintain existing ones.\n- **Code-Splitting**: File-based routing allows TanStack Router to automatically code-split your routes for better performance.\n- **Type-Safety**: File-based routing raises the ceiling on type-safety by generating managing type linkages for your routes, which can otherwise be a tedious process via code-based routing.\n- **Consistency**: File-based routing enforces a consistent structure for your routes, making it easier to maintain and update your application and move from one project to another.\n\n## `/`s or `.`s?\n\nWhile directories have long been used to represent route hierarchy, file-based routing introduces an additional concept of using the `.` character in the file-name to denote a route nesting. This allows you to avoid creating directories for few deeply nested routes and continue to use directories for wider route hierarchies. Let's take a look at some examples!\n\n## Directory Routes\n\nDirectories can be used to denote route hierarchy, which can be useful for organizing multiple routes into logical groups and also cutting down on the filename length for large groups of deeply nested routes.\n\nSee the example below:\n\n| Filename | Route Path | Component Output |\n| ----------------------- | ------------------------- | --------------------------------- |\n| \u02A6 `__root.tsx` | | `<Root>` |\n| \u02A6 `index.tsx` | `/` (exact) | `<Root><RootIndex>` |\n| \u02A6 `about.tsx` | `/about` | `<Root><About>` |\n| \u02A6 `posts.tsx` | `/posts` | `<Root><Posts>` |\n| \uD83D\uDCC2 `posts` | | |\n| \u2504 \u02A6 `index.tsx` | `/posts` (exact) | `<Root><Posts><PostsIndex>` |\n| \u2504 \u02A6 `$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n| \uD83D\uDCC2 `posts_` | | |\n| \u2504 \uD83D\uDCC2 `$postId` | | |\n| \u2504 \u2504 \u02A6 `edit.tsx` | `/posts/$postId/edit` | `<Root><EditPost>` |\n| \u02A6 `settings.tsx` | `/settings` | `<Root><Settings>` |\n| \uD83D\uDCC2 `settings` | | `<Root><Settings>` |\n| \u2504 \u02A6 `profile.tsx` | `/settings/profile` | `<Root><Settings><Profile>` |\n| \u2504 \u02A6 `notifications.tsx` | `/settings/notifications` | `<Root><Settings><Notifications>` |\n| \u02A6 `_pathlessLayout.tsx` | | `<Root><PathlessLayout>` |\n| \uD83D\uDCC2 `_pathlessLayout` | | |\n| \u2504 \u02A6 `route-a.tsx` | `/route-a` | `<Root><PathlessLayout><RouteA>` |\n| \u2504 \u02A6 `route-b.tsx` | `/route-b` | `<Root><PathlessLayout><RouteB>` |\n| \uD83D\uDCC2 `files` | | |\n| \u2504 \u02A6 `$.tsx` | `/files/$` | `<Root><Files>` |\n| \uD83D\uDCC2 `account` | | |\n| \u2504 \u02A6 `route.tsx` | `/account` | `<Root><Account>` |\n| \u2504 \u02A6 `overview.tsx` | `/account/overview` | `<Root><Account><Overview>` |\n\n## Flat Routes\n\nFlat routing gives you the ability to use `.`s to denote route nesting levels.\n\nThis can be useful when you have a large number of uniquely deeply nested routes and want to avoid creating directories for each one:\n\nSee the example below:\n\n| Filename | Route Path | Component Output |\n| ------------------------------- | ------------------------- | --------------------------------- |\n| \u02A6 `__root.tsx` | | `<Root>` |\n| \u02A6 `index.tsx` | `/` (exact) | `<Root><RootIndex>` |\n| \u02A6 `about.tsx` | `/about` | `<Root><About>` |\n| \u02A6 `posts.tsx` | `/posts` | `<Root><Posts>` |\n| \u02A6 `posts.index.tsx` | `/posts` (exact) | `<Root><Posts><PostsIndex>` |\n| \u02A6 `posts.$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n| \u02A6 `posts_.$postId.edit.tsx` | `/posts/$postId/edit` | `<Root><EditPost>` |\n| \u02A6 `settings.tsx` | `/settings` | `<Root><Settings>` |\n| \u02A6 `settings.profile.tsx` | `/settings/profile` | `<Root><Settings><Profile>` |\n| \u02A6 `settings.notifications.tsx` | `/settings/notifications` | `<Root><Settings><Notifications>` |\n| \u02A6 `_pathlessLayout.tsx` | | `<Root><PathlessLayout>` |\n| \u02A6 `_pathlessLayout.route-a.tsx` | `/route-a` | `<Root><PathlessLayout><RouteA>` |\n| \u02A6 `_pathlessLayout.route-b.tsx` | `/route-b` | `<Root><PathlessLayout><RouteB>` |\n| \u02A6 `files.$.tsx` | `/files/$` | `<Root><Files>` |\n| \u02A6 `account.tsx` | `/account` | `<Root><Account>` |\n| \u02A6 `account.overview.tsx` | `/account/overview` | `<Root><Account><Overview>` |\n\n## Mixed Flat and Directory Routes\n\nIt's extremely likely that a 100% directory or flat route structure won't be the best fit for your project, which is why TanStack Router allows you to mix both flat and directory routes together to create a route tree that uses the best of both worlds where it makes sense:\n\nSee the example below:\n\n| Filename | Route Path | Component Output |\n| ------------------------------ | ------------------------- | --------------------------------- |\n| \u02A6 `__root.tsx` | | `<Root>` |\n| \u02A6 `index.tsx` | `/` (exact) | `<Root><RootIndex>` |\n| \u02A6 `about.tsx` | `/about` | `<Root><About>` |\n| \u02A6 `posts.tsx` | `/posts` | `<Root><Posts>` |\n| \uD83D\uDCC2 `posts` | | |\n| \u2504 \u02A6 `index.tsx` | `/posts` (exact) | `<Root><Posts><PostsIndex>` |\n| \u2504 \u02A6 `$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n| \u2504 \u02A6 `$postId.edit.tsx` | `/posts/$postId/edit` | `<Root><Posts><Post><EditPost>` |\n| \u02A6 `settings.tsx` | `/settings` | `<Root><Settings>` |\n| \u02A6 `settings.profile.tsx` | `/settings/profile` | `<Root><Settings><Profile>` |\n| \u02A6 `settings.notifications.tsx` | `/settings/notifications` | `<Root><Settings><Notifications>` |\n| \u02A6 `account.tsx` | `/account` | `<Root><Account>` |\n| \u02A6 `account.overview.tsx` | `/account/overview` | `<Root><Account><Overview>` |\n\nBoth flat and directory routes can be mixed together to create a route tree that uses the best of both worlds where it makes sense.\n\n> [!TIP]\n> If you find that the default file-based routing structure doesn't fit your needs, you can always use [Virtual File Routes](../virtual-file-routes.md) to control the source of your routes whilst still getting the awesome performance benefits of file-based routing.\n\n## Getting started with File-Based Routing\n\nTo get started with file-based routing, you'll need to configure your project's bundler to use the TanStack Router Plugin or the TanStack Router CLI.\n\nTo enable file-based routing, you'll need to be using React with a supported bundler. See if your bundler is listed in the configuration guides below.\n\n[//]: # 'SupportedBundlersList'\n\n- [Installation with Vite](../../installation/with-vite)\n- [Installation with Rspack/Rsbuild](../../installation/with-rspack)\n- [Installation with Webpack](../../installation/with-webpack)\n- [Installation with Esbuild](../../installation/with-esbuild)\n\n[//]: # 'SupportedBundlersList'\n\nWhen using TanStack Router's file-based routing through one of the supported bundlers, our plugin will **automatically generate your route configuration through your bundler's dev and build processes**. It is the easiest way to use TanStack Router's route generation features.\n\nIf your bundler is not yet supported, you can reach out to us on Discord or GitHub to let us know.\n\n# File Naming Conventions\n\nFile-based routing requires that you follow a few simple file naming conventions to ensure that your routes are generated correctly. The concepts these conventions enable are covered in detail in the [Route Trees & Nesting](../route-trees.md) guide.\n\n| Feature | Description |\n| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **`__root.tsx`** | The root route file must be named `__root.tsx` and must be placed in the root of the configured `routesDirectory`. |\n| **`.` Separator** | Routes can use the `.` character to denote a nested route. For example, `blog.post` will be generated as a child of `blog`. |\n| **`$` Token** | Route segments with the `$` token are parameterized and will extract the value from the URL pathname as a route `param`. |\n| **`_` Prefix** | Route segments with the `_` prefix are considered to be pathless layout routes and will not be used when matching its child routes against the URL pathname. |\n| **`_` Suffix** | Route segments with the `_` suffix exclude the route from being nested under any parent routes. |\n| **`-` Prefix** | Files and folders with the `-` prefix are excluded from the route tree. They will not be added to the `routeTree.gen.ts` file and can be used to colocate logic in route folders. |\n| **`(folder)` folder name pattern** | A folder that matches this pattern is treated as a **route group**, preventing the folder from being included in the route's URL path. |\n| **`[x]` Escaping** | Square brackets escape special characters in filenames that would otherwise have routing meaning. For example, `script[.]js.tsx` becomes `/script.js` and `api[.]v1.tsx` becomes `/api.v1`. |\n| **`index` Token** | Route segments ending with the `index` token (before any file extensions) will match the parent route when the URL pathname matches the parent route exactly. This can be configured via the `indexToken` configuration option, see [options](../../../../api/file-based-routing.md#indextoken). |\n| **`.route.tsx` File Type** | When using directories to organise routes, the `route` suffix can be used to create a route file at the directory's path. For example, `blog.post.route.tsx` or `blog/post/route.tsx` can be used as the route file for the `/blog/post` route. This can be configured via the `routeToken` configuration option, see [options](../../../../api/file-based-routing.md#routetoken). |\n\n> **\uD83D\uDCA1 Remember:** The file-naming conventions for your project could be affected by what [options](../../../../api/file-based-routing.md) are configured.\n\n> [!NOTE] To escape a trailing underscore, for example `/posts[_].tsx`, usage of the upgraded [Non-Nested Routes](../routing-concepts#non-nested-routes) is required.\n\n## Dynamic Path Params\n\nDynamic path params can be used in both flat and directory routes to create routes that can match a dynamic segment of the URL path. Dynamic path params are denoted by the `$` character in the filename:\n\n| Filename | Route Path | Component Output |\n| --------------------- | ---------------- | --------------------- |\n| ... | ... | ... |\n| \u02A6 `posts.$postId.tsx` | `/posts/$postId` | `<Root><Posts><Post>` |\n\nWe'll learn more about dynamic path params in the [Path Params](../../guide/path-params.md) guide.\n\n## Pathless Routes\n\nPathless routes wrap child routes with either logic or a component without requiring a URL path. Non-path routes are denoted by the `_` character in the filename:\n\n| Filename | Route Path | Component Output |\n| -------------- | ---------- | ---------------- |\n| \u02A6 `_app.tsx` | | |\n| \u02A6 `_app.a.tsx` | /a | `<Root><App><A>` |\n| \u02A6 `_app.b.tsx` | /b | `<Root><App><B>` |\n\nTo learn more about pathless routes, see the [Routing Concepts - Pathless Routes](../routing-concepts.md#pathless-layout-routes) guide.\n\n# Route Matching\n\nRoute matching follows a consistent and predictable pattern. This guide will explain how route trees are matched.\n\nWhen TanStack Router processes your route tree, all of your routes are automatically sorted to match the most specific routes first. This means that regardless of the order your route tree is defined, routes will always be sorted in this order:\n\n- Index Route\n- Static Routes (most specific to least specific)\n- Dynamic Routes (longest to shortest)\n- Splat/Wildcard Routes\n\nConsider the following pseudo route tree:\n\n```\nRoot\n - blog\n - $postId\n - /\n - new\n - /\n - *\n - about\n - about/us\n```\n\nAfter sorting, this route tree will become:\n\n```\nRoot\n - /\n - about/us\n - about\n - blog\n - /\n - new\n - $postId\n - *\n```\n\nThis final order represents the order in which routes will be matched based on specificity.\n\nUsing that route tree, let's follow the matching process for a few different URLs:\n\n- `/blog`\n ```\n Root\n \u274C /\n \u274C about/us\n \u274C about\n \u23E9 blog\n \u2705 /\n - new\n - $postId\n - *\n ```\n- `/blog/my-post`\n ```\n Root\n \u274C /\n \u274C about/us\n \u274C about\n \u23E9 blog\n \u274C /\n \u274C new\n \u2705 $postId\n - *\n ```\n- `/`\n ```\n Root\n \u2705 /\n - about/us\n - about\n - blog\n - /\n - new\n - $postId\n - *\n ```\n- `/not-a-route`\n ```\n Root\n \u274C /\n \u274C about/us\n \u274C about\n \u274C blog\n - /\n - new\n - $postId\n \u2705 *\n ```\n\n# Route Trees\n\nTanStack Router uses a nested route tree to match up the URL with the correct component tree to render.\n\nTo build a route tree, TanStack Router supports:\n\n- [File-Based Routing](../file-based-routing.md)\n- [Code-Based Routing](../code-based-routing.md)\n\nBoth methods support the exact same core features and functionality, but **file-based routing requires less code for the same or better results**. For this reason, **file-based routing is the preferred and recommended way** to configure TanStack Router. Most of the documentation is written from the perspective of file-based routing.\n\n## Route Trees\n\nNested routing is a powerful concept that allows you to use a URL to render a nested component tree. For example, given the URL of `/blog/posts/123`, you could create a route hierarchy that looks like this:\n\n```tsx\n\u251C\u2500\u2500 blog\n\u2502 \u251C\u2500\u2500 posts\n\u2502 \u2502 \u251C\u2500\u2500 $postId\n```\n\nAnd render a component tree that looks like this:\n\n```tsx\n<Blog>\n <Posts>\n <Post postId=\"123\" />\n </Posts>\n</Blog>\n```\n\nLet's take that concept and expand it out to a larger site structure, but with file-names now:\n\n```\n/routes\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 about.tsx\n\u251C\u2500\u2500 posts/\n\u2502 \u251C\u2500\u2500 index.tsx\n\u2502 \u251C\u2500\u2500 $postId.tsx\n\u251C\u2500\u2500 posts.$postId.edit.tsx\n\u251C\u2500\u2500 settings/\n\u2502 \u251C\u2500\u2500 profile.tsx\n\u2502 \u251C\u2500\u2500 notifications.tsx\n\u251C\u2500\u2500 _pathlessLayout/\n\u2502 \u251C\u2500\u2500 route-a.tsx\n\u251C\u2500\u2500 \u251C\u2500\u2500 route-b.tsx\n\u251C\u2500\u2500 files/\n\u2502 \u251C\u2500\u2500 $.tsx\n```\n\nThe above is a valid route tree configuration that can be used with TanStack Router! There's a lot of power and convention to unpack with file-based routing, so let's break it down a bit.\n\n## Route Tree Configuration\n\nRoute trees can be configured using a few different ways:\n\n- [Flat Routes](../file-based-routing.md#flat-routes)\n- [Directories](../file-based-routing.md#directory-routes)\n- [Mixed Flat Routes and Directories](../file-based-routing.md#mixed-flat-and-directory-routes)\n- [Virtual File Routes](../virtual-file-routes.md)\n- [Code-Based Routes](../code-based-routing.md)\n\nPlease be sure to check out the full documentation links above for each type of route tree, or just proceed to the next section to get started with file-based routing.\n\n# Routing Concepts\n\nTanStack Router supports a number of powerful routing concepts that allow you to build complex and dynamic routing systems with ease.\n\nEach of these concepts is useful and powerful, and we'll dive into each of them in the following sections.\n\n## Anatomy of a Route\n\nAll other routes, other than the [Root Route](#the-root-route), are configured using the `createFileRoute` function, which provides type safety when using file-based routing:\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n component: PostsComponent,\n})\n```\n\nThe `createFileRoute` function takes a single argument, the file-route's path as a string.\n\n**\u2753\u2753\u2753 \"Wait, you're making me pass the path of the route file to `createFileRoute`?\"**\n\nYes! But don't worry, this path is **automatically written and managed by the router for you via the TanStack Router Bundler Plugin or Router CLI.** So, as you create new routes, move routes around or rename routes, the path will be updated for you automatically.\n\nThe reason for this pathname has everything to do with the magical type safety of TanStack Router. Without this pathname, TypeScript would have no idea what file we're in! (We wish TypeScript had a built-in for this, but they don't yet \uD83E\uDD37\u200D\u2642\uFE0F)\n\n## The Root Route\n\nThe root route is the top-most route in the entire tree and encapsulates all other routes as children.\n\n- It has no path\n- It is **always** matched\n- Its `component` is **always** rendered\n\nEven though it doesn't have a path, the root route has access to all of the same functionality as other routes including:\n\n- components\n- loaders\n- search param validation\n- etc.\n\nTo create a root route, call the `createRootRoute()` function and export it as the `Route` variable in your route file:\n\n```tsx\n// Standard root route\nimport { createRootRoute } from '@tanstack/react-router'\n\nexport const Route = createRootRoute()\n\n// Root route with Context\nimport { createRootRouteWithContext } from '@tanstack/react-router'\nimport type { QueryClient } from '@tanstack/react-query'\n\nexport interface MyRouterContext {\n queryClient: QueryClient\n}\nexport const Route = createRootRouteWithContext<MyRouterContext>()\n```\n\nTo learn more about Context in TanStack Router, see the [Router Context](../../guide/router-context.md) guide.\n\n## Basic Routes\n\nBasic routes match a specific path, for example `/about`, `/settings`, `/settings/notifications` are all basic routes, as they match the path exactly.\n\nLet's take a look at an `/about` route:\n\n```tsx\n// about.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/about')({\n component: AboutComponent,\n})\n\nfunction AboutComponent() {\n return <div>About</div>\n}\n```\n\nBasic routes are simple and straightforward. They match the path exactly and render the provided component.\n\n## Index Routes\n\nIndex routes specifically target their parent route when it is **matched exactly and no child route is matched**.\n\nLet's take a look at an index route for a `/posts` URL:\n\n```tsx\n// posts.index.tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\n// Note the trailing slash, which is used to target index routes\nexport const Route = createFileRoute('/posts/')({\n component: PostsIndexComponent,\n})\n\nfunction PostsIndexComponent() {\n return <div>Please select a post!</div>\n}\n```\n\nThis route will be matched when the URL is `/posts` exactly.\n\n## Dynamic Route Segments\n\nRoute path segments that start with a `$` followed by a label are dynamic and capture that section of the URL into the `params` object for use in your application. For example, a pathname of `/posts/123` would match the `/posts/$postId` route, and the `params` object would be `{ postId: '123' }`.\n\nThese params are then usable in your route's configuration and components! Let's look at a `posts.$postId.tsx` route:\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/$postId')({\n // In a loader\n loader: ({ params }) => fetchPost(params.postId),\n // Or in a component\n component: PostComponent,\n})\n\nfunction PostComponent() {\n // In a component!\n const { postId } = Route.useParams()\n return <div>Post ID: {postId}</div>\n}\n```\n\n> \uD83E\uDDE0 Dynamic segments work at **each** segment of the path. For example, you could have a route with the path of `/posts/$postId/$revisionId` and each `$` segment would be captured into the `params` object.\n\n## Splat / Catch-All Routes\n\nA route with a path of only `$` is called a \"splat\" route because it _always_ captures _any_ remaining section of the URL pathname from the `$` to the end. The captured pathname is then available in the `params` object under the special `_splat` property.\n\nFor example, a route targeting the `files/$` path is a splat route. If the URL pathname is `/files/documents/hello-world`, the `params` object would contain `documents/hello-world` under the special `_splat` property:\n\n```js\n{\n '_splat': 'documents/hello-world'\n}\n```\n\n> \u26A0\uFE0F In v1 of the router, splat routes are also denoted with a `*` instead of a `_splat` key for backwards compatibility. This will be removed in v2.\n\n> \uD83E\uDDE0 Why use `$`? Thanks to tools like Remix, we know that despite `*`s being the most common character to represent a wildcard, they do not play nice with filenames or CLI tools, so just like them, we decided to use `$` instead.\n\n## Optional Path Parameters\n\nOptional path parameters allow you to define route segments that may or may not be present in the URL. They use the `{-$paramName}` syntax and provide flexible routing patterns where certain parameters are optional.\n\n```tsx\n// posts.{-$category}.tsx - Optional category parameter\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/{-$category}')({\n component: PostsComponent,\n})\n\nfunction PostsComponent() {\n const { category } = Route.useParams()\n\n return <div>{category ? `Posts in ${category}` : 'All Posts'}</div>\n}\n```\n\nThis route will match both `/posts` (category is `undefined`) and `/posts/tech` (category is `\"tech\"`).\n\nYou can also define multiple optional parameters in a single route:\n\n```tsx\n// posts.{-$category}.{-$slug}.tsx\nexport const Route = createFileRoute('/posts/{-$category}/{-$slug}')({\n component: PostsComponent,\n})\n```\n\nThis route matches `/posts`, `/posts/tech`, and `/posts/tech/hello-world`.\n\n> \uD83E\uDDE0 Routes with optional parameters are ranked lower in priority than exact matches, ensuring that more specific routes like `/posts/featured` are matched before `/posts/{-$category}`.\n\n## Layout Routes\n\nLayout routes are used to wrap child routes with additional components and logic. They are useful for:\n\n- Wrapping child routes with a layout component\n- Enforcing a `loader` requirement before displaying any child routes\n- Validating and providing search params to child routes\n- Providing fallbacks for error components or pending elements to child routes\n- Providing shared context to all child routes\n- And more!\n\nLet's take a look at an example layout route called `app.tsx`:\n\n```\nroutes/\n\u251C\u2500\u2500 app.tsx\n\u251C\u2500\u2500 app.dashboard.tsx\n\u251C\u2500\u2500 app.settings.tsx\n```\n\nIn the tree above, `app.tsx` is a layout route that wraps two child routes, `app.dashboard.tsx` and `app.settings.tsx`.\n\nThis tree structure is used to wrap the child routes with a layout component:\n\n```tsx\nimport { Outlet, createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/app')({\n component: AppLayoutComponent,\n})\n\nfunction AppLayoutComponent() {\n return (\n <div>\n <h1>App Layout</h1>\n <Outlet />\n </div>\n )\n}\n```\n\nThe following table shows which component(s) will be rendered based on the URL:\n\n| URL Path | Component |\n| ---------------- | ------------------------ |\n| `/app` | `<AppLayout>` |\n| `/app/dashboard` | `<AppLayout><Dashboard>` |\n| `/app/settings` | `<AppLayout><Settings>` |\n\nSince TanStack Router supports mixed flat and directory routes, you can also express your application's routing using layout routes within directories:\n\n```\nroutes/\n\u251C\u2500\u2500 app/\n\u2502 \u251C\u2500\u2500 route.tsx\n\u2502 \u251C\u2500\u2500 dashboard.tsx\n\u2502 \u251C\u2500\u2500 settings.tsx\n```\n\nIn this nested tree, the `app/route.tsx` file is a configuration for the layout route that wraps two child routes, `app/dashboard.tsx` and `app/settings.tsx`.\n\nLayout Routes also let you enforce component and loader logic for Dynamic Route Segments:\n\n```\nroutes/\n\u251C\u2500\u2500 app/users/\n\u2502 \u251C\u2500\u2500 $userId/\n| | \u251C\u2500\u2500 route.tsx\n| | \u251C\u2500\u2500 index.tsx\n| | \u251C\u2500\u2500 edit.tsx\n```\n\n## Pathless Layout Routes\n\nLike [Layout Routes](#layout-routes), Pathless Layout Routes are used to wrap child routes with additional components and logic. However, pathless layout routes do not require a matching `path` in the URL and are used to wrap child routes with additional components and logic without requiring a matching `path` in the URL.\n\nPathless Layout Routes are prefixed with an underscore (`_`) to denote that they are \"pathless\".\n\n> \uD83E\uDDE0 The part of the path after the `_` prefix is used as the route's ID and is required because every route must be uniquely identifiable, especially when using TypeScript so as to avoid type errors and accomplish autocomplete effectively.\n\nLet's take a look at an example route called `_pathlessLayout.tsx`:\n\n```\n\nroutes/\n\u251C\u2500\u2500 _pathlessLayout.tsx\n\u251C\u2500\u2500 _pathlessLayout.a.tsx\n\u251C\u2500\u2500 _pathlessLayout.b.tsx\n\n```\n\nIn the tree above, `_pathlessLayout.tsx` is a pathless layout route that wraps two child routes, `_pathlessLayout.a.tsx` and `_pathlessLayout.b.tsx`.\n\nThe `_pathlessLayout.tsx` route is used to wrap the child routes with a Pathless layout component:\n\n```tsx\nimport { Outlet, createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/_pathlessLayout')({\n component: PathlessLayoutComponent,\n})\n\nfunction PathlessLayoutComponent() {\n return (\n <div>\n <h1>Pathless layout</h1>\n <Outlet />\n </div>\n )\n}\n```\n\nThe following table shows which component will be rendered based on the URL:\n\n| URL Path | Component |\n| -------- | --------------------- |\n| `/` | `<Index>` |\n| `/a` | `<PathlessLayout><A>` |\n| `/b` | `<PathlessLayout><B>` |\n\nSince TanStack Router supports mixed flat and directory routes, you can also express your application's routing using pathless layout routes within directories:\n\n```\nroutes/\n\u251C\u2500\u2500 _pathlessLayout/\n\u2502 \u251C\u2500\u2500 route.tsx\n\u2502 \u251C\u2500\u2500 a.tsx\n\u2502 \u251C\u2500\u2500 b.tsx\n```\n\nHowever, unlike Layout Routes, since Pathless Layout Routes do match based on URL path segments, this means that these routes do not support [Dynamic Route Segments](#dynamic-route-segments) as part of their path and therefore cannot be matched in the URL.\n\nThis means that you cannot do this:\n\n```\nroutes/\n\u251C\u2500\u2500 _$postId/ \u274C\n\u2502 \u251C\u2500\u2500 ...\n```\n\nRather, you'd have to do this:\n\n```\nroutes/\n\u251C\u2500\u2500 $postId/\n\u251C\u2500\u2500 _postPathlessLayout/ \u2705\n\u2502 \u251C\u2500\u2500 ...\n```\n\n## Non-Nested Routes\n\nNon-nested routes can be created by suffixing a parent file route segment with a `_` and are used to **un-nest** a route from its parents and render its own component tree.\n\nConsider the following flat route tree:\n\n```\nroutes/\n\u251C\u2500\u2500 posts.tsx\n\u251C\u2500\u2500 posts.$postId.tsx\n\u251C\u2500\u2500 posts_.$postId.edit.tsx\n```\n\nThe following table shows which component will be rendered based on the URL:\n\n| URL Path | Component |\n| ----------------- | ---------------------------- |\n| `/posts` | `<Posts>` |\n| `/posts/123` | `<Posts><Post postId=\"123\">` |\n| `/posts/123/edit` | `<PostEditor postId=\"123\">` |\n\n- The `posts.$postId.tsx` route is nested as normal under the `posts.tsx` route and will render `<Posts><Post>`.\n- The `posts_.$postId.edit.tsx` route **does not share** the same `posts` prefix as the other routes and therefore will be treated as if it is a top-level route and will render `<PostEditor>`.\n\n> [!NOTE]\n> While using non-nested routes with file-based routing already works brilliantly, it might misbehave in certain conditions.\n> Many of these limitations have already been addressed and will be released in the next major version of TanStack Router.\n>\n> To start enjoying these benefits early, you can enable the experimental `nonNestedRoutes` flag in the router plugin configuration:\n>\n> ```ts\n> export default defineConfig({\n> plugins: [\n> tanstackRouter({\n> // some config,\n> experimental: {\n> nonNestedRoutes: true,\n> },\n> }),\n> ],\n> })\n> ```\n>\n> _It is important to note that this does bring a slight change in how non-nested routes are referenced in useParams, useNavigate, etc. For this reason this has been released as a feature flag.\n> The trailing underscore is no longer expected in the path:_\n>\n> Previously:\n>\n> ```ts\n> useParams({ from: '/posts_/$postId/edit' })\n> ```\n>\n> Now:\n>\n> ```ts\n> useParams({ from: '/posts/$postId/edit' })\n> ```\n\n## Excluding Files and Folders from Routes\n\nFiles and folders can be excluded from route generation with a `-` prefix attached to the file name. This gives you the ability to colocate logic in the route directories.\n\nConsider the following route tree:\n\n```\nroutes/\n\u251C\u2500\u2500 posts.tsx\n\u251C\u2500\u2500 -posts-table.tsx // \uD83D\uDC48\uD83C\uDFFC ignored\n\u251C\u2500\u2500 -components/ // \uD83D\uDC48\uD83C\uDFFC ignored\n\u2502 \u251C\u2500\u2500 header.tsx // \uD83D\uDC48\uD83C\uDFFC ignored\n\u2502 \u251C\u2500\u2500 footer.tsx // \uD83D\uDC48\uD83C\uDFFC ignored\n\u2502 \u251C\u2500\u2500 ...\n```\n\nWe can import from the excluded files into our posts route\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\nimport { PostsTable } from './-posts-table'\nimport { PostsHeader } from './-components/header'\nimport { PostsFooter } from './-components/footer'\n\nexport const Route = createFileRoute('/posts')({\n loader: () => fetchPosts(),\n component: PostComponent,\n})\n\nfunction PostComponent() {\n const posts = Route.useLoaderData()\n\n return (\n <div>\n <PostsHeader />\n <PostsTable posts={posts} />\n <PostsFooter />\n </div>\n )\n}\n```\n\nThe excluded files will not be added to `routeTree.gen.ts`.\n\n## Pathless Route Group Directories\n\nPathless route group directories use `()` as a way to group routes files together regardless of their path. They are purely organizational and do not affect the route tree or component tree in any way.\n\n```\nroutes/\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 (app)/\n\u2502 \u251C\u2500\u2500 dashboard.tsx\n\u2502 \u251C\u2500\u2500 settings.tsx\n\u2502 \u251C\u2500\u2500 users.tsx\n\u251C\u2500\u2500 (auth)/\n\u2502 \u251C\u2500\u2500 login.tsx\n\u2502 \u251C\u2500\u2500 register.tsx\n```\n\nIn the example above, the `app` and `auth` directories are purely organizational and do not affect the route tree or component tree in any way. They are used to group related routes together for easier navigation and organization.\n\nThe following table shows which component will be rendered based on the URL:\n\n| URL Path | Component |\n| ------------ | ------------- |\n| `/` | `<Index>` |\n| `/dashboard` | `<Dashboard>` |\n| `/settings` | `<Settings>` |\n| `/users` | `<Users>` |\n| `/login` | `<Login>` |\n| `/register` | `<Register>` |\n\nAs you can see, the `app` and `auth` directories are purely organizational and do not affect the route tree or component tree in any way.\n\n# Virtual File Routes\n\n> We'd like to thank the Remix team for [pioneering the concept of virtual file routes](https://www.youtube.com/watch?v=fjTX8hQTlEc&t=730s). We've taken inspiration from their work and adapted it to work with TanStack Router's existing file-based route-tree generation.\n\nVirtual file routes are a powerful concept that allows you to build a route tree programmatically using code that references real files in your project. This can be useful if:\n\n- You have an existing route organization that you want to keep.\n- You want to customize the location of your route files.\n- You want to completely override TanStack Router's file-based route generation and build your own convention.\n\nHere's a quick example of using virtual file routes to map a route tree to a set of real files in your project:\n\n```tsx\n// routes.ts\nimport {\n rootRoute,\n route,\n index,\n layout,\n physical,\n} from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n index('index.tsx'),\n layout('pathlessLayout.tsx', [\n route('/dashboard', 'app/dashboard.tsx', [\n index('app/dashboard-index.tsx'),\n route('/invoices', 'app/dashboard-invoices.tsx', [\n index('app/invoices-index.tsx'),\n route('$id', 'app/invoice-detail.tsx'),\n ]),\n ]),\n physical('/posts', 'posts'),\n ]),\n])\n```\n\n## Configuration\n\nVirtual file routes can be configured either via:\n\n- The `TanStackRouter` plugin for Vite/Rspack/Webpack\n- The `tsr.config.json` file for the TanStack Router CLI\n\n## Configuration via the TanStackRouter Plugin\n\nIf you're using the `TanStackRouter` plugin for Vite/Rspack/Webpack, you can configure virtual file routes by passing the path of your routes file to the `virtualRoutesConfig` option when setting up the 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\nexport default defineConfig({\n plugins: [\n tanstackRouter({\n target: 'react',\n virtualRouteConfig: './routes.ts',\n }),\n react(),\n ],\n})\n```\n\nOr, you choose to define the virtual routes directly in the configuration:\n\n```tsx\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\nimport { tanstackRouter } from '@tanstack/router-plugin/vite'\nimport { rootRoute } from '@tanstack/virtual-file-routes'\n\nconst routes = rootRoute('root.tsx', [\n // ... the rest of your virtual route tree\n])\n\nexport default defineConfig({\n plugins: [tanstackRouter({ virtualRouteConfig: routes }), react()],\n})\n```\n\n## Creating Virtual File Routes\n\nTo create virtual file routes, you'll need to import the `@tanstack/virtual-file-routes` package. This package provides a set of functions that allow you to create virtual routes that reference real files in your project. A few utility functions are exported from the package:\n\n- `rootRoute` - Creates a virtual root route.\n- `route` - Creates a virtual route.\n- `index` - Creates a virtual index route.\n- `layout` - Creates a virtual pathless layout route.\n- `physical` - Creates a physical virtual route (more on this later).\n\n## Virtual Root Route\n\nThe `rootRoute` function is used to create a virtual root route. It takes a file name and an array of children routes. Here's an example of a virtual root route:\n\n```tsx\n// routes.ts\nimport { rootRoute } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n // ... children routes\n])\n```\n\n## Virtual Route\n\nThe `route` function is used to create a virtual route. It takes a path, a file name, and an array of children routes. Here's an example of a virtual route:\n\n```tsx\n// routes.ts\nimport { route } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n route('/about', 'about.tsx', [\n // ... children routes\n ]),\n])\n```\n\nYou can also define a virtual route without a file name. This allows to set a common path prefix for its children:\n\n```tsx\n// routes.ts\nimport { route } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n route('/hello', [\n route('/world', 'world.tsx'), // full path will be \"/hello/world\"\n route('/universe', 'universe.tsx'), // full path will be \"/hello/universe\"\n ]),\n])\n```\n\n## Virtual Index Route\n\nThe `index` function is used to create a virtual index route. It takes a file name. Here's an example of a virtual index route:\n\n```tsx\nimport { index } from '@tanstack/virtual-file-routes'\n\nconst routes = rootRoute('root.tsx', [index('index.tsx')])\n```\n\n## Virtual Pathless Route\n\nThe `layout` function is used to create a virtual pathless route. It takes a file name, an array of children routes, and an optional pathless ID. Here's an example of a virtual pathless route:\n\n```tsx\n// routes.ts\nimport { layout } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n layout('pathlessLayout.tsx', [\n // ... children routes\n ]),\n])\n```\n\nYou can also specify a pathless ID to give the route a unique identifier that is different from the filename:\n\n```tsx\n// routes.ts\nimport { layout } from '@tanstack/virtual-file-routes'\n\nexport const routes = rootRoute('root.tsx', [\n layout('my-pathless-layout-id', 'pathlessLayout.tsx', [\n // ... children routes\n ]),\n])\n```\n\n## Physical Virtual Routes\n\nPhysical virtual routes are a way to \"mount\" a directory of good ol' TanStack Router File Based routing convention under a specific URL path. This can be useful if you are using virtual routes to customize a small portion of your route tree high up in the hierarchy, but want to use the standard file-based routing convention for sub-routes and directories.\n\nConsider the following file structure:\n\n```\n/routes\n\u251C\u2500\u2500 root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 pathlessLayout.tsx\n\u251C\u2500\u2500 app\n\u2502 \u251C\u2500\u2500 dashboard.tsx\n\u2502 \u251C\u2500\u2500 dashboard-index.tsx\n\u2502 \u251C\u2500\u2500 dashboard-invoices.tsx\n\u2502 \u251C\u2500\u2500 invoices-index.tsx\n\u2502 \u251C\u2500\u2500 invoice-detail.tsx\n\u2514\u2500\u2500 posts\n \u251C\u2500\u2500 index.tsx\n \u251C\u2500\u2500 $postId.tsx\n \u251C\u2500\u2500 $postId.edit.tsx\n \u251C\u2500\u2500 comments/\n \u2502 \u251C\u2500\u2500 index.tsx\n \u2502 \u251C\u2500\u2500 $commentId.tsx\n \u2514\u2500\u2500 likes/\n \u251C\u2500\u2500 index.tsx\n \u251C\u2500\u2500 $likeId.tsx\n```\n\nLet's use virtual routes to customize our route tree for everything but `posts`, then use physical virtual routes to mount the `posts` directory under the `/posts` path:\n\n```tsx\n// routes.ts\nexport const routes = rootRoute('root.tsx', [\n // Set up your virtual routes as normal\n index('index.tsx'),\n layout('pathlessLayout.tsx', [\n route('/dashboard', 'app/dashboard.tsx', [\n index('app/dashboard-index.tsx'),\n route('/invoices', 'app/dashboard-invoices.tsx', [\n index('app/invoices-index.tsx'),\n route('$id', 'app/invoice-detail.tsx'),\n ]),\n ]),\n // Mount the `posts` directory under the `/posts` path\n physical('/posts', 'posts'),\n ]),\n])\n```\n\n## Virtual Routes inside of TanStack Router File Based routing\n\nThe previous section showed you how you can use TanStack Router's File Based routing convention inside of a virtual route configuration.\nHowever, the opposite is possible as well. \nYou can configure the main part of your app's route tree using TanStack Router's File Based routing convention and opt into virtual route configuration for specific subtrees.\n\nConsider the following file structure:\n\n```\n/routes\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 foo\n\u2502 \u251C\u2500\u2500 bar\n\u2502 \u2502 \u251C\u2500\u2500 __virtual.ts\n\u2502 \u2502 \u251C\u2500\u2500 details.tsx\n\u2502 \u2502 \u251C\u2500\u2500 home.tsx\n\u2502 \u2502 \u2514\u2500\u2500 route.ts\n\u2502 \u2514\u2500\u2500 bar.tsx\n\u2514\u2500\u2500 index.tsx\n```\n\nLet's look at the `bar` directory which contains a special file named `__virtual.ts`. This file instructs the generator to switch over to virtual file route configuration for this directory (and its child directories).\n\n`__virtual.ts` configures the virtual routes for that particular subtree of the route tree. It uses the same API as explained above, with the only difference being that no `rootRoute` is defined for that subtree:\n\n```tsx\n// routes/foo/bar/__virtual.ts\nimport {\n defineVirtualSubtreeConfig,\n index,\n route,\n} from '@tanstack/virtual-file-routes'\n\nexport default defineVirtualSubtreeConfig([\n index('home.tsx'),\n route('$id', 'details.tsx'),\n])\n```\n\nThe helper function `defineVirtualSubtreeConfig` is closely modeled after vite's `defineConfig` and allows you to define a subtree configuration via a default export. The default export can either be\n\n- a subtree config object\n- a function returning a subtree config object\n- an async function returning a subtree config object\n\n## Inception\n\nYou can mix and match TanStack Router's File Based routing convention and virtual route configuration however you like. \nLet's go deeper! \nCheck out the following example that starts off using File Based routing convention, switches over to virtual route configuration for `/posts`, switches back to File Based routing convention for `/posts/lets-go` only to switch over to virtual route configuration again for `/posts/lets-go/deeper`.\n\n```\n\u251C\u2500\u2500 __root.tsx\n\u251C\u2500\u2500 index.tsx\n\u251C\u2500\u2500 posts\n\u2502 \u251C\u2500\u2500 __virtual.ts\n\u2502 \u251C\u2500\u2500 details.tsx\n\u2502 \u251C\u2500\u2500 home.tsx\n\u2502 \u2514\u2500\u2500 lets-go\n\u2502 \u251C\u2500\u2500 deeper\n\u2502 \u2502 \u251C\u2500\u2500 __virtual.ts\n\u2502 \u2502 \u2514\u2500\u2500 home.tsx\n\u2502 \u2514\u2500\u2500 index.tsx\n\u2514\u2500\u2500 posts.tsx\n```\n\n## Configuration via the TanStack Router CLI\n\nIf you're using the TanStack Router CLI, you can configure virtual file routes by defining the path to your routes file in the `tsr.config.json` file:\n\n```json\n// tsr.config.json\n{\n \"virtualRouteConfig\": \"./routes.ts\"\n}\n```\n\nOr you can define the virtual routes directly in the configuration, while much less common allows you to configure them via the TanStack Router CLI by adding a `virtualRouteConfig` object to your `tsr.config.json` file and defining your virtual routes and passing the resulting JSON that is generated by calling the actual `rootRoute`/`route`/`index`/etc functions from the `@tanstack/virtual-file-routes` package:\n\n```json\n// tsr.config.json\n{\n \"virtualRouteConfig\": {\n \"type\": \"root\",\n \"file\": \"root.tsx\",\n \"children\": [\n {\n \"type\": \"index\",\n \"file\": \"home.tsx\"\n },\n {\n \"type\": \"route\",\n \"file\": \"posts/posts.tsx\",\n \"path\": \"/posts\",\n \"children\": [\n {\n \"type\": \"index\",\n \"file\": \"posts/posts-home.tsx\"\n },\n {\n \"type\": \"route\",\n \"file\": \"posts/posts-detail.tsx\",\n \"path\": \"$postId\"\n }\n ]\n },\n {\n \"type\": \"layout\",\n \"id\": \"first\",\n \"file\": \"layout/first-pathless-layout.tsx\",\n \"children\": [\n {\n \"type\": \"layout\",\n \"id\": \"second\",\n \"file\": \"layout/second-pathless-layout.tsx\",\n \"children\": [\n {\n \"type\": \"route\",\n \"file\": \"a.tsx\",\n \"path\": \"/route-a\"\n },\n {\n \"type\": \"route\",\n \"file\": \"b.tsx\",\n \"path\": \"/route-b\"\n }\n ]\n }\n ]\n }\n ]\n }\n}\n```\n\n";
|
|
2
2
|
export default _default;
|
|
@@ -573,6 +573,8 @@ File-based routing requires that you follow a few simple file naming conventions
|
|
|
573
573
|
|
|
574
574
|
> **💡 Remember:** The file-naming conventions for your project could be affected by what [options](../../../../api/file-based-routing.md) are configured.
|
|
575
575
|
|
|
576
|
+
> [!NOTE] To escape a trailing underscore, for example \`/posts[_].tsx\`, usage of the upgraded [Non-Nested Routes](../routing-concepts#non-nested-routes) is required.
|
|
577
|
+
|
|
576
578
|
## Dynamic Path Params
|
|
577
579
|
|
|
578
580
|
Dynamic path params can be used in both flat and directory routes to create routes that can match a dynamic segment of the URL path. Dynamic path params are denoted by the \`$\` character in the filename:
|
|
@@ -1106,6 +1108,40 @@ The following table shows which component will be rendered based on the URL:
|
|
|
1106
1108
|
- The \`posts.$postId.tsx\` route is nested as normal under the \`posts.tsx\` route and will render \`<Posts><Post>\`.
|
|
1107
1109
|
- The \`posts_.$postId.edit.tsx\` route **does not share** the same \`posts\` prefix as the other routes and therefore will be treated as if it is a top-level route and will render \`<PostEditor>\`.
|
|
1108
1110
|
|
|
1111
|
+
> [!NOTE]
|
|
1112
|
+
> While using non-nested routes with file-based routing already works brilliantly, it might misbehave in certain conditions.
|
|
1113
|
+
> Many of these limitations have already been addressed and will be released in the next major version of TanStack Router.
|
|
1114
|
+
>
|
|
1115
|
+
> To start enjoying these benefits early, you can enable the experimental \`nonNestedRoutes\` flag in the router plugin configuration:
|
|
1116
|
+
>
|
|
1117
|
+
> \`\`\`ts
|
|
1118
|
+
> export default defineConfig({
|
|
1119
|
+
> plugins: [
|
|
1120
|
+
> tanstackRouter({
|
|
1121
|
+
> // some config,
|
|
1122
|
+
> experimental: {
|
|
1123
|
+
> nonNestedRoutes: true,
|
|
1124
|
+
> },
|
|
1125
|
+
> }),
|
|
1126
|
+
> ],
|
|
1127
|
+
> })
|
|
1128
|
+
> \`\`\`
|
|
1129
|
+
>
|
|
1130
|
+
> _It is important to note that this does bring a slight change in how non-nested routes are referenced in useParams, useNavigate, etc. For this reason this has been released as a feature flag.
|
|
1131
|
+
> The trailing underscore is no longer expected in the path:_
|
|
1132
|
+
>
|
|
1133
|
+
> Previously:
|
|
1134
|
+
>
|
|
1135
|
+
> \`\`\`ts
|
|
1136
|
+
> useParams({ from: '/posts_/$postId/edit' })
|
|
1137
|
+
> \`\`\`
|
|
1138
|
+
>
|
|
1139
|
+
> Now:
|
|
1140
|
+
>
|
|
1141
|
+
> \`\`\`ts
|
|
1142
|
+
> useParams({ from: '/posts/$postId/edit' })
|
|
1143
|
+
> \`\`\`
|
|
1144
|
+
|
|
1109
1145
|
## Excluding Files and Folders from Routes
|
|
1110
1146
|
|
|
1111
1147
|
Files and folders can be excluded from route generation with a \`-\` prefix attached to the file name. This gives you the ability to colocate logic in the route directories.
|