@tanstack/react-router
Version:
Modern and scalable routing for React applications
1,203 lines (906 loc) • 75.1 kB
JavaScript
export default `# Code-Based Routing
> [!TIP]
> Code-based routing is not recommended for most applications. It is recommended to use [File-Based Routing](../file-based-routing.md) instead.
## ⚠️ Before You Start
- If you're using [File-Based Routing](../file-based-routing.md), **skip this guide**.
- 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.
## Route Trees
Code-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.
Let's consider the same route tree from the [Route Trees & Nesting](../route-trees.md#route-trees) guide, and convert it to code-based routing:
Here is the file-based version:
\`\`\`
routes/
├── __root.tsx
├── index.tsx
├── about.tsx
├── posts/
│ ├── index.tsx
│ ├── $postId.tsx
├── posts.$postId.edit.tsx
├── settings/
│ ├── profile.tsx
│ ├── notifications.tsx
├── _pathlessLayout.tsx
├── _pathlessLayout/
│ ├── route-a.tsx
├── ├── route-b.tsx
├── files/
│ ├── $.tsx
\`\`\`
And here is a summarized code-based version:
\`\`\`tsx
import { createRootRoute, createRoute } from '@tanstack/react-router'
const rootRoute = createRootRoute()
const indexRoute = createRoute({
getParentRoute: () => rootRoute,
path: '/',
})
const aboutRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'about',
})
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts',
})
const postsIndexRoute = createRoute({
getParentRoute: () => postsRoute,
path: '/',
})
const postRoute = createRoute({
getParentRoute: () => postsRoute,
path: '$postId',
})
const postEditorRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts/$postId/edit',
})
const settingsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'settings',
})
const profileRoute = createRoute({
getParentRoute: () => settingsRoute,
path: 'profile',
})
const notificationsRoute = createRoute({
getParentRoute: () => settingsRoute,
path: 'notifications',
})
const pathlessLayoutRoute = createRoute({
getParentRoute: () => rootRoute,
id: 'pathlessLayout',
})
const pathlessLayoutARoute = createRoute({
getParentRoute: () => pathlessLayoutRoute,
path: 'route-a',
})
const pathlessLayoutBRoute = createRoute({
getParentRoute: () => pathlessLayoutRoute,
path: 'route-b',
})
const filesRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'files/$',
})
\`\`\`
## Anatomy of a Route
All other routes other than the root route are configured using the \`createRoute\` function:
\`\`\`tsx
const route = createRoute({
getParentRoute: () => rootRoute,
path: '/posts',
component: PostsComponent,
})
\`\`\`
The \`getParentRoute\` option is a function that returns the parent route of the route you're creating.
**❓❓❓ "Wait, you're making me pass the parent route for every route I make?"**
Absolutely! 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!
> [!IMPORTANT]
> For every route that **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.
When 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:
| Path | Normalized Path |
| -------- | --------------- |
| \`/\` | \`/\` |
| \`/about\` | \`about\` |
| \`about/\` | \`about\` |
| \`about\` | \`about\` |
| \`$\` | \`$\` |
| \`/$\` | \`$\` |
| \`/$/\` | \`$\` |
## Manually building the route tree
When 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.
\`\`\`tsx
/* prettier-ignore */
const routeTree = rootRoute.addChildren([
indexRoute,
aboutRoute,
postsRoute.addChildren([
postsIndexRoute,
postRoute,
]),
postEditorRoute,
settingsRoute.addChildren([
profileRoute,
notificationsRoute,
]),
pathlessLayoutRoute.addChildren([
pathlessLayoutARoute,
pathlessLayoutBRoute,
]),
filesRoute.addChildren([
fileRoute,
]),
])
/* prettier-ignore-end */
\`\`\`
But before you can go ahead and build the route tree, you need to understand how the Routing Concepts for Code-Based Routing work.
## Routing Concepts for Code-Based Routing
Believe 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.
We're going to assume you've read the [Routing Concepts](../routing-concepts.md) guide and are familiar with each of these main concepts:
- The Root Route
- Basic Routes
- Index Routes
- Dynamic Route Segments
- Splat / Catch-All Routes
- Layout Routes
- Pathless Routes
- Non-Nested Routes
Now, let's take a look at how to create each of these route types in code.
## The Root Route
Creating a root route in code-based routing is thankfully the same as doing so in file-based routing. Call the \`createRootRoute()\` function.
Unlike 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).
\`\`\`tsx
// Standard root route
import { createRootRoute } from '@tanstack/react-router'
const rootRoute = createRootRoute()
// Root route with Context
import { createRootRouteWithContext } from '@tanstack/react-router'
import type { QueryClient } from '@tanstack/react-query'
export interface MyRouterContext {
queryClient: QueryClient
}
const rootRoute = createRootRouteWithContext<MyRouterContext>()
\`\`\`
To learn more about Context in TanStack Router, see the [Router Context](../../guide/router-context.md) guide.
## Basic Routes
To create a basic route, simply provide a normal \`path\` string to the \`createRoute\` function:
\`\`\`tsx
const aboutRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'about',
})
\`\`\`
See, it's that simple! The \`aboutRoute\` will match the URL \`/about\`.
## Index Routes
Unlike 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:
\`\`\`tsx
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts',
})
const postsIndexRoute = createRoute({
getParentRoute: () => postsRoute,
// Notice the single slash \`/\` here
path: '/',
})
\`\`\`
So, the \`postsIndexRoute\` will match the URL \`/posts/\` (or \`/posts\`).
## Dynamic Route Segments
Dynamic 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\`:
\`\`\`tsx
const postIdRoute = createRoute({
getParentRoute: () => postsRoute,
path: '$postId',
// In a loader
loader: ({ params }) => fetchPost(params.postId),
// Or in a component
component: PostComponent,
})
function PostComponent() {
const { postId } = postIdRoute.useParams()
return <div>Post ID: {postId}</div>
}
\`\`\`
> [!TIP]
> 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.
## Splat / Catch-All Routes
As 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:
\`\`\`tsx
const filesRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'files',
})
const fileRoute = createRoute({
getParentRoute: () => filesRoute,
path: '$',
})
\`\`\`
For the URL \`/documents/hello-world\`, the \`params\` object will look like this:
\`\`\`js
{
'_splat': 'documents/hello-world'
}
\`\`\`
## Layout Routes
Layout 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:
\`\`\`tsx
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts',
component: PostsLayoutComponent, // The layout component
})
function PostsLayoutComponent() {
return (
<div>
<h1>Posts</h1>
<Outlet />
</div>
)
}
const postsIndexRoute = createRoute({
getParentRoute: () => postsRoute,
path: '/',
})
const postsCreateRoute = createRoute({
getParentRoute: () => postsRoute,
path: 'create',
})
const routeTree = rootRoute.addChildren([
// The postsRoute is the layout route
// Its children will be nested under the PostsLayoutComponent
postsRoute.addChildren([postsIndexRoute, postsCreateRoute]),
])
\`\`\`
Now, both the \`postsIndexRoute\` and \`postsCreateRoute\` will render their contents inside of the \`PostsLayoutComponent\`:
\`\`\`tsx
// URL: /posts
<PostsLayoutComponent>
<PostsIndexComponent />
</PostsLayoutComponent>
// URL: /posts/create
<PostsLayoutComponent>
<PostsCreateComponent />
</PostsLayoutComponent>
\`\`\`
## Pathless Layout Routes
In 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.
\`\`\`tsx
const pathlessLayoutRoute = createRoute({
getParentRoute: () => rootRoute,
id: 'pathlessLayout',
component: PathlessLayoutComponent,
})
function PathlessLayoutComponent() {
return (
<div>
<h1>Pathless Layout</h1>
<Outlet />
</div>
)
}
const pathlessLayoutARoute = createRoute({
getParentRoute: () => pathlessLayoutRoute,
path: 'route-a',
})
const pathlessLayoutBRoute = createRoute({
getParentRoute: () => pathlessLayoutRoute,
path: 'route-b',
})
const routeTree = rootRoute.addChildren([
// The pathless layout route has no path, only an id
// So its children will be nested under the pathless layout route
pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]),
])
\`\`\`
Now both \`/route-a\` and \`/route-b\` will render their contents inside of the \`PathlessLayoutComponent\`:
\`\`\`tsx
// URL: /route-a
<PathlessLayoutComponent>
<RouteAComponent />
</PathlessLayoutComponent>
// URL: /route-b
<PathlessLayoutComponent>
<RouteBComponent />
</PathlessLayoutComponent>
\`\`\`
## Non-Nested Routes
Building 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:
- \`/posts_/$postId/edit\`
- \`/posts\`
- \`$postId\`
To 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):
\`\`\`tsx
// The posts editor route is nested under the root route
const postEditorRoute = createRoute({
getParentRoute: () => rootRoute,
// The path includes the entire path we need to match
path: 'posts/$postId/edit',
})
const postsRoute = createRoute({
getParentRoute: () => rootRoute,
path: 'posts',
})
const postRoute = createRoute({
getParentRoute: () => postsRoute,
path: '$postId',
})
const routeTree = rootRoute.addChildren([
// The post editor route is nested under the root route
postEditorRoute,
postsRoute.addChildren([postRoute]),
])
\`\`\`
# File-Based Routing
Most 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.
## What is File-Based Routing?
File-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:
- **Simplicity**: File-based routing is visually intuitive and easy to understand for both new and experienced developers.
- **Organization**: Routes are organized in a way that mirrors the URL structure of your application.
- **Scalability**: As your application grows, file-based routing makes it easy to add new routes and maintain existing ones.
- **Code-Splitting**: File-based routing allows TanStack Router to automatically code-split your routes for better performance.
- **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.
- **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.
## \`/\`s or \`.\`s?
While 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!
## Directory Routes
Directories 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.
See the example below:
| Filename | Route Path | Component Output |
| ----------------------- | ------------------------- | --------------------------------- |
| ʦ \`__root.tsx\` | | \`<Root>\` |
| ʦ \`index.tsx\` | \`/\` (exact) | \`<Root><RootIndex>\` |
| ʦ \`about.tsx\` | \`/about\` | \`<Root><About>\` |
| ʦ \`posts.tsx\` | \`/posts\` | \`<Root><Posts>\` |
| 📂 \`posts\` | | |
| ┄ ʦ \`index.tsx\` | \`/posts\` (exact) | \`<Root><Posts><PostsIndex>\` |
| ┄ ʦ \`$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
| 📂 \`posts_\` | | |
| ┄ 📂 \`$postId\` | | |
| ┄ ┄ ʦ \`edit.tsx\` | \`/posts/$postId/edit\` | \`<Root><EditPost>\` |
| ʦ \`settings.tsx\` | \`/settings\` | \`<Root><Settings>\` |
| 📂 \`settings\` | | \`<Root><Settings>\` |
| ┄ ʦ \`profile.tsx\` | \`/settings/profile\` | \`<Root><Settings><Profile>\` |
| ┄ ʦ \`notifications.tsx\` | \`/settings/notifications\` | \`<Root><Settings><Notifications>\` |
| ʦ \`_pathlessLayout.tsx\` | | \`<Root><PathlessLayout>\` |
| 📂 \`_pathlessLayout\` | | |
| ┄ ʦ \`route-a.tsx\` | \`/route-a\` | \`<Root><PathlessLayout><RouteA>\` |
| ┄ ʦ \`route-b.tsx\` | \`/route-b\` | \`<Root><PathlessLayout><RouteB>\` |
| 📂 \`files\` | | |
| ┄ ʦ \`$.tsx\` | \`/files/$\` | \`<Root><Files>\` |
| 📂 \`account\` | | |
| ┄ ʦ \`route.tsx\` | \`/account\` | \`<Root><Account>\` |
| ┄ ʦ \`overview.tsx\` | \`/account/overview\` | \`<Root><Account><Overview>\` |
## Flat Routes
Flat routing gives you the ability to use \`.\`s to denote route nesting levels.
This can be useful when you have a large number of uniquely deeply nested routes and want to avoid creating directories for each one:
See the example below:
| Filename | Route Path | Component Output |
| ------------------------------- | ------------------------- | --------------------------------- |
| ʦ \`__root.tsx\` | | \`<Root>\` |
| ʦ \`index.tsx\` | \`/\` (exact) | \`<Root><RootIndex>\` |
| ʦ \`about.tsx\` | \`/about\` | \`<Root><About>\` |
| ʦ \`posts.tsx\` | \`/posts\` | \`<Root><Posts>\` |
| ʦ \`posts.index.tsx\` | \`/posts\` (exact) | \`<Root><Posts><PostsIndex>\` |
| ʦ \`posts.$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
| ʦ \`posts_.$postId.edit.tsx\` | \`/posts/$postId/edit\` | \`<Root><EditPost>\` |
| ʦ \`settings.tsx\` | \`/settings\` | \`<Root><Settings>\` |
| ʦ \`settings.profile.tsx\` | \`/settings/profile\` | \`<Root><Settings><Profile>\` |
| ʦ \`settings.notifications.tsx\` | \`/settings/notifications\` | \`<Root><Settings><Notifications>\` |
| ʦ \`_pathlessLayout.tsx\` | | \`<Root><PathlessLayout>\` |
| ʦ \`_pathlessLayout.route-a.tsx\` | \`/route-a\` | \`<Root><PathlessLayout><RouteA>\` |
| ʦ \`_pathlessLayout.route-b.tsx\` | \`/route-b\` | \`<Root><PathlessLayout><RouteB>\` |
| ʦ \`files.$.tsx\` | \`/files/$\` | \`<Root><Files>\` |
| ʦ \`account.tsx\` | \`/account\` | \`<Root><Account>\` |
| ʦ \`account.overview.tsx\` | \`/account/overview\` | \`<Root><Account><Overview>\` |
## Mixed Flat and Directory Routes
It'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:
See the example below:
| Filename | Route Path | Component Output |
| ------------------------------ | ------------------------- | --------------------------------- |
| ʦ \`__root.tsx\` | | \`<Root>\` |
| ʦ \`index.tsx\` | \`/\` (exact) | \`<Root><RootIndex>\` |
| ʦ \`about.tsx\` | \`/about\` | \`<Root><About>\` |
| ʦ \`posts.tsx\` | \`/posts\` | \`<Root><Posts>\` |
| 📂 \`posts\` | | |
| ┄ ʦ \`index.tsx\` | \`/posts\` (exact) | \`<Root><Posts><PostsIndex>\` |
| ┄ ʦ \`$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
| ┄ ʦ \`$postId.edit.tsx\` | \`/posts/$postId/edit\` | \`<Root><Posts><Post><EditPost>\` |
| ʦ \`settings.tsx\` | \`/settings\` | \`<Root><Settings>\` |
| ʦ \`settings.profile.tsx\` | \`/settings/profile\` | \`<Root><Settings><Profile>\` |
| ʦ \`settings.notifications.tsx\` | \`/settings/notifications\` | \`<Root><Settings><Notifications>\` |
| ʦ \`account.tsx\` | \`/account\` | \`<Root><Account>\` |
| ʦ \`account.overview.tsx\` | \`/account/overview\` | \`<Root><Account><Overview>\` |
Both flat and directory routes can be mixed together to create a route tree that uses the best of both worlds where it makes sense.
> [!TIP]
> 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.
## Getting started with File-Based Routing
To 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.
To 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.
[//]: # 'SupportedBundlersList'
- [Installation with Vite](../installation-with-vite.md)
- [Installation with Rspack/Rsbuild](../installation-with-rspack.md)
- [Installation with Webpack](../installation-with-webpack.md)
- [Installation with Esbuild](../installation-with-esbuild.md)
[//]: # 'SupportedBundlersList'
When 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.
If your bundler is not yet supported, you can reach out to us on Discord or GitHub to let us know. Till then, fear not! You can still use the [\`@tanstack/router-cli\`](../installation-with-router-cli.md) package to generate your route tree file.
# File Naming Conventions
File-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.
| Feature | Description |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **\`__root.tsx\`** | The root route file must be named \`__root.tsx\` and must be placed in the root of the configured \`routesDirectory\`. |
| **\`.\` Separator** | Routes can use the \`.\` character to denote a nested route. For example, \`blog.post\` will be generated as a child of \`blog\`. |
| **\`$\` Token** | Route segments with the \`$\` token are parameterized and will extract the value from the URL pathname as a route \`param\`. |
| **\`_\` 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. |
| **\`_\` Suffix** | Route segments with the \`_\` suffix exclude the route from being nested under any parent routes. |
| **\`-\` 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. |
| **\`(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. |
| **\`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). |
| **\`.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). |
> **💡 Remember:** The file-naming conventions for your project could be affected by what [options](../../../../api/file-based-routing.md) are configured.
## Dynamic Path Params
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:
| Filename | Route Path | Component Output |
| --------------------- | ---------------- | --------------------- |
| ... | ... | ... |
| ʦ \`posts.$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
We'll learn more about dynamic path params in the [Path Params](../../guide/path-params.md) guide.
## Pathless Routes
Pathless 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:
| Filename | Route Path | Component Output |
| -------------- | ---------- | ---------------- |
| ʦ \`_app.tsx\` | | |
| ʦ \`_app.a.tsx\` | /a | \`<Root><App><A>\` |
| ʦ \`_app.b.tsx\` | /b | \`<Root><App><B>\` |
To learn more about pathless routes, see the [Routing Concepts - Pathless Routes](../routing-concepts.md#pathless-layout-routes) guide.
# Installation with Vite
[//]: # 'BundlerConfiguration'
To use file-based routing with **Esbuild**, you'll need to install the \`@tanstack/router-plugin\` package.
\`\`\`sh
npm install -D @tanstack/router-plugin
\`\`\`
Once installed, you'll need to add the plugin to your configuration.
\`\`\`tsx
// esbuild.config.js
import { tanstackRouter } from '@tanstack/router-plugin/esbuild'
export default {
// ...
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
}
\`\`\`
Or, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-esbuild-file-based) and get started.
Now that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router.
[//]: # 'BundlerConfiguration'
## Ignoring the generated route tree file
If 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.
Here are some resources to help you ignore the generated route tree file:
- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
> [!WARNING]
> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
You 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:
\`\`\`json
{
"files.readonlyInclude": {
"**/routeTree.gen.ts": true
},
"files.watcherExclude": {
"**/routeTree.gen.ts": true
},
"search.exclude": {
"**/routeTree.gen.ts": true
}
}
\`\`\`
You 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.
## Configuration
When using the TanStack Router Plugin with Esbuild for File-based routing, it comes with some sane defaults that should work for most projects:
\`\`\`json
{
"routesDirectory": "./src/routes",
"generatedRouteTree": "./src/routeTree.gen.ts",
"routeFileIgnorePrefix": "-",
"quoteStyle": "single"
}
\`\`\`
If 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.
You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
# Installation with Router CLI
> [!WARNING]
> 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.
To use file-based routing with the TanStack Router CLI, you'll need to install the \`@tanstack/router-cli\` package.
\`\`\`sh
npm install -D @tanstack/router-cli
\`\`\`
Once installed, you'll need to amend your your scripts in your \`package.json\` for the CLI to \`watch\` and \`generate\` files.
\`\`\`json
{
"scripts": {
"generate-routes": "tsr generate",
"watch-routes": "tsr watch",
"build": "npm run generate-routes && ...",
"dev": "npm run watch-routes && ..."
}
}
\`\`\`
[//]: # 'AfterScripts'
[//]: # 'AfterScripts'
You 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.
With the CLI installed, the following commands are made available via the \`tsr\` command
## Using the \`generate\` command
Generates the routes for a project based on the provided configuration.
\`\`\`sh
tsr generate
\`\`\`
## Using the \`watch\` command
Continuously watches the specified directories and regenerates routes as needed.
**Usage:**
\`\`\`sh
tsr watch
\`\`\`
With 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.
## Ignoring the generated route tree file
If 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.
Here are some resources to help you ignore the generated route tree file:
- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
> [!WARNING]
> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
You 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:
\`\`\`json
{
"files.readonlyInclude": {
"**/routeTree.gen.ts": true
},
"files.watcherExclude": {
"**/routeTree.gen.ts": true
},
"search.exclude": {
"**/routeTree.gen.ts": true
}
}
\`\`\`
You 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.
## Configuration
When using the TanStack Router CLI for File-based routing, it comes with some sane defaults that should work for most projects:
\`\`\`json
{
"routesDirectory": "./src/routes",
"generatedRouteTree": "./src/routeTree.gen.ts",
"routeFileIgnorePrefix": "-",
"quoteStyle": "single"
}
\`\`\`
If 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.
[//]: # 'TargetConfiguration'
[//]: # 'TargetConfiguration'
You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
# Installation with Rspack
[//]: # 'BundlerConfiguration'
To use file-based routing with **Rspack** or **Rsbuild**, you'll need to install the \`@tanstack/router-plugin\` package.
\`\`\`sh
npm install -D @tanstack/router-plugin
\`\`\`
Once installed, you'll need to add the plugin to your configuration.
\`\`\`tsx
// rsbuild.config.ts
import { defineConfig } from '@rsbuild/core'
import { pluginReact } from '@rsbuild/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/rspack'
export default defineConfig({
plugins: [pluginReact()],
tools: {
rspack: {
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
},
},
})
\`\`\`
Or, you can clone our [Quickstart Rspack/Rsbuild example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-rspack-file-based) and get started.
Now that you've added the plugin to your Rspack/Rsbuild configuration, you're all set to start using file-based routing with TanStack Router.
[//]: # 'BundlerConfiguration'
## Ignoring the generated route tree file
If 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.
Here are some resources to help you ignore the generated route tree file:
- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
> [!WARNING]
> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
You 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:
\`\`\`json
{
"files.readonlyInclude": {
"**/routeTree.gen.ts": true
},
"files.watcherExclude": {
"**/routeTree.gen.ts": true
},
"search.exclude": {
"**/routeTree.gen.ts": true
}
}
\`\`\`
You 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.
## Configuration
When 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:
\`\`\`json
{
"routesDirectory": "./src/routes",
"generatedRouteTree": "./src/routeTree.gen.ts",
"routeFileIgnorePrefix": "-",
"quoteStyle": "single"
}
\`\`\`
If 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.
You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
# Installation with Vite
[//]: # 'BundlerConfiguration'
To use file-based routing with **Vite**, you'll need to install the \`@tanstack/router-plugin\` package.
\`\`\`sh
npm install -D @tanstack/router-plugin
\`\`\`
Once installed, you'll need to add the plugin to your Vite configuration.
\`\`\`ts
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { tanstackRouter } from '@tanstack/router-plugin/vite'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
// Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
react(),
// ...
],
})
\`\`\`
Or, you can clone our [Quickstart Vite example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-file-based) and get started.
> [!WARNING]
> 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.
Now that you've added the plugin to your Vite configuration, you're all set to start using file-based routing with TanStack Router.
[//]: # 'BundlerConfiguration'
## Ignoring the generated route tree file
If 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.
Here are some resources to help you ignore the generated route tree file:
- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
> [!WARNING]
> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
You 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:
\`\`\`json
{
"files.readonlyInclude": {
"**/routeTree.gen.ts": true
},
"files.watcherExclude": {
"**/routeTree.gen.ts": true
},
"search.exclude": {
"**/routeTree.gen.ts": true
}
}
\`\`\`
You 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.
## Configuration
When using the TanStack Router Plugin with Vite for File-based routing, it comes with some sane defaults that should work for most projects:
\`\`\`json
{
"routesDirectory": "./src/routes",
"generatedRouteTree": "./src/routeTree.gen.ts",
"routeFileIgnorePrefix": "-",
"quoteStyle": "single"
}
\`\`\`
If 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.
You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
# Installation with Webpack
[//]: # 'BundlerConfiguration'
To use file-based routing with **Webpack**, you'll need to install the \`@tanstack/router-plugin\` package.
\`\`\`sh
npm install -D @tanstack/router-plugin
\`\`\`
Once installed, you'll need to add the plugin to your configuration.
\`\`\`tsx
// webpack.config.ts
import { tanstackRouter } from '@tanstack/router-plugin/webpack'
export default {
plugins: [
tanstackRouter({
target: 'react',
autoCodeSplitting: true,
}),
],
}
\`\`\`
Or, you can clone our [Quickstart Webpack example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-webpack-file-based) and get started.
Now that you've added the plugin to your Webpack configuration, you're all set to start using file-based routing with TanStack Router.
[//]: # 'BundlerConfiguration'
## Ignoring the generated route tree file
If 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.
Here are some resources to help you ignore the generated route tree file:
- Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
- ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
- Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
> [!WARNING]
> If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
You 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:
\`\`\`json
{
"files.readonlyInclude": {
"**/routeTree.gen.ts": true
},
"files.watcherExclude": {
"**/routeTree.gen.ts": true
},
"search.exclude": {
"**/routeTree.gen.ts": true
}
}
\`\`\`
You 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.
## Configuration
When using the TanStack Router Plugin with Webpack for File-based routing, it comes with some sane defaults that should work for most projects:
\`\`\`json
{
"routesDirectory": "./src/routes",
"generatedRouteTree": "./src/routeTree.gen.ts",
"routeFileIgnorePrefix": "-",
"quoteStyle": "single"
}
\`\`\`
If 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.
You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
# Route Matching
Route matching follows a consistent and predictable pattern. This guide will explain how route trees are matched.
When 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:
- Index Route
- Static Routes (most specific to least specific)
- Dynamic Routes (longest to shortest)
- Splat/Wildcard Routes
Consider the following pseudo route tree:
\`\`\`
Root
- blog
- $postId
- /
- new
- /
- *
- about
- about/us
\`\`\`
After sorting, this route tree will become:
\`\`\`
Root
- /
- about/us
- about
- blog
- /
- new
- $postId
- *
\`\`\`
This final order represents the order in which routes will be matched based on specificity.
Using that route tree, let's follow the matching process for a few different URLs:
- \`/blog\`
\`\`\`
Root
❌ /
❌ about/us
❌ about
⏩ blog
✅ /
- new
- $postId
- *
\`\`\`
- \`/blog/my-post\`
\`\`\`
Root
❌ /
❌ about/us
❌ about
⏩ blog
❌ /
❌ new
✅ $postId
- *
\`\`\`
- \`/\`
\`\`\`
Root
✅ /
- about/us
- about
- blog
- /
- new
- $postId
- *
\`\`\`
- \`/not-a-route\`
\`\`\`
Root
❌ /
❌ about/us
❌ about
❌ blog
- /
- new
- $postId
✅ *
\`\`\`
# Route Trees
TanStack Router uses a nested route tree to match up the URL with the correct component tree to render.
To build a route tree, TanStack Router supports:
- [File-Based Routing](../file-based-routing.md)
- [Code-Based Routing](../code-based-routing.md)
Both 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.
## Route Trees
Nested 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:
\`\`\`tsx
├── blog
│ ├── posts
│ │ ├── $postId
\`\`\`
And render a component tree that looks like this:
\`\`\`tsx
<Blog>
<Posts>
<Post postId="123" />
</Posts>
</Blog>
\`\`\`
Let's take that concept and expand it out to a larger site structure, but with file-names now:
\`\`\`
/routes
├── __root.tsx
├── index.tsx
├── about.tsx
├── posts/
│ ├── index.tsx
│ ├── $postId.tsx
├── posts.$postId.edit.tsx
├── settings/
│ ├── profile.tsx
│ ├── notifications.tsx
├── _pathlessLayout/
│ ├── route-a.tsx
├── ├── route-b.tsx
├── files/
│ ├── $.tsx
\`\`\`
The 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.
## Route Tree Configuration
Route trees can be configured using a few different ways:
- [Flat Routes](../file-based-routing.md#flat-routes)
- [Directories](../file-based-routing.md#directory-routes)
- [Mixed Flat Routes and Directories](../file-based-routing.md#mixed-flat-and-directory-routes)
- [Virtual File Routes](../virtual-file-routes.md)
- [Code-Based Routes](../code-based-routing.md)
Please 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.
# Routing Concepts
TanStack Router supports a number of powerful routing concepts that allow you to build complex and dynamic routing systems with ease.
Each of these concepts is useful and powerful, and we'll dive into each of them in the following sections.
## Anatomy of a Route
All other routes, other than the [Root Route](#t