Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

routing.md

233 lines7.1 KB

1---
2id: routing
3title: Routing
4---
5​
6TanStack Start is built on top of TanStack Router, so all of the features of TanStack Router are available to you.
7​
8> [!NOTE]
9> We highly recommend reading the [TanStack Router documentation](/router/latest/docs/framework/react/overview) to learn more about the features and capabilities of TanStack Router. What you learn here is more of a high-level overview of TanStack Router and how it works in Start.
10​
11## The Router
12​
13The `router.tsx` file is the file that will dictate the behavior of TanStack Router used within Start. It's located in the `src` directory of your project.
14​
15```
16src/
17β”œβ”€β”€ router.tsx
18```
19​
20Here, you can configure everything from the default [preloading functionality](/router/latest/docs/framework/react/guide/preloading) to [caching staleness](/router/latest/docs/framework/react/guide/data-loading).
21​
22```tsx
23// src/router.tsx
24import { createRouter } from '@tanstack/react-router'
25import { routeTree } from './routeTree.gen'
26​
27// You must export a getRouter function that
28// returns a new router instance each time
29export function getRouter() {
30 const router = createRouter({
31 routeTree,
32 scrollRestoration: true,
33 })
34​
35 return router
37```
38​
39## File-Based Routing
40​
41Start uses TanStack Router's file-based routing approach to ensure proper code-splitting and advanced type-safety.
42​
43You can find your routes in the `src/routes` directory.
44​
45```
46src/
47β”œβ”€β”€ routes <-- This is where you put your routes
48β”‚ β”œβ”€β”€ __root.tsx
49β”‚ β”œβ”€β”€ index.tsx
50β”‚ β”œβ”€β”€ about.tsx
51β”‚ β”œβ”€β”€ posts.tsx
52β”‚ β”œβ”€β”€ posts/$postId.tsx
53```
54​
55## The Root Route
56​
57The root route is the top-most route in the entire tree and encapsulates all other routes as children. It's found in the `src/routes/__root.tsx` file and must be named `__root.tsx`.
58​
59```
60src/
61β”œβ”€β”€ routes
62β”‚ β”œβ”€β”€ __root.tsx <-- The root route
63```
64​
65- It has no path and is **always** matched
66- Its `component` is **always** rendered
67- This is where you render your document shell, e.g. `<html>`, `<body>`, etc.
68- Because it is **always rendered**, it is the perfect place to construct your application shell and take care of any global logic
69​
70```tsx
71// src/routes/__root.tsx
72import {
73 Outlet,
74 createRootRoute,
75 HeadContent,
76 Scripts,
77} from '@tanstack/react-router'
78import type { ReactNode } from 'react'
79​
80export const Route = createRootRoute({
81 head: () => ({
82 meta: [
83 {
84 charSet: 'utf-8',
85 },
86 {
87 name: 'viewport',
88 content: 'width=device-width, initial-scale=1',
89 },
90 {
91 title: 'TanStack Start Starter',
92 },
93 ],
94 }),
95 component: RootComponent,
96})
97​
98function RootComponent() {
99 return (
100 <RootDocument>
101 <Outlet />
102 </RootDocument>
103 )
105​
106function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
107 return (
108 <html>
109 <head>
110 <HeadContent />
111 </head>
112 <body>
113 {children}
114 <Scripts />
115 </body>
116 </html>
117 )
119```
120​
121Notice the `Scripts` component at the bottom of the `<body>` tag. This is used to load all of the client-side JavaScript for the application and should always be included for proper functionality.
122​
123## The HeadContent Component
124​
125The `HeadContent` component is used to render the head, title, meta, link, and head-related script tags of the document.
126​
127It should be **rendered in the `<head>` tag of your root route's layout.**
128​
129## The Outlet Component
130​
131The `Outlet` component is used to render the next potentially matching child route. `<Outlet />` doesn't take any props and can be rendered anywhere within a route's component tree. If there is no matching child route, `<Outlet />` will render `null`.
132​
133## The Scripts Component
134​
135The `Scripts` component is used to render the body scripts of the document.
136​
137It should be **rendered in the `<body>` tag of your root route's layout.**
138​
139## Route Tree Generation
140​
141You may notice a `routeTree.gen.ts` file in your project.
142​
143```
144src/
145β”œβ”€β”€ routeTree.gen.ts <-- The generated route tree file
146```
147​
148This file is automatically generated when you run TanStack Start (via `npm run dev` or `npm run start`). This file contains the generated route tree and a handful of TS utilities that make TanStack Start's type-safety extremely fast and fully inferred.
149​
150## Nested Routing
151​
152TanStack Router uses nested routing to match the URL with the correct component tree to render.
153​
154For example, given the following routes:
155​
156```
157routes/
158β”œβ”€β”€ __root.tsx <-- Renders the <Root> component
159β”œβ”€β”€ posts.tsx <-- Renders the <Posts> component
160β”œβ”€β”€ posts.$postId.tsx <-- Renders the <Post> component
161```
162​
163And the URL: `/posts/123`
164​
165The component tree would look like this:
166​
167```
168<Root>
169 <Posts>
170 <Post />
171 </Posts>
172</Root>
173```
174​
175## Types of Routes
176​
177There are a few different types of routes that you can create in your project.
178​
179- Index Routes - Matched when the URL is exactly the same as the route's path
180- Dynamic/Wildcard/Splat Routes - Dynamically capture part or all of the URL path into a variable to use in your application
181​
182There are also a few different utility route types that you can use to group and organize your routes
183​
184- Pathless Layout Routes (Apply layout or logic to a group of routes without nesting them in a path)
185- Non-Nested Routes (Un-nest a route from its parents and render its own component tree)
186- Grouped Routes (Group routes together in a directory simply for organization, without affecting the path hierarchy)
187​
188## Route Tree Configuration
189​
190The route tree is configured in the `src/routes` directory.
191​
192## Creating File Routes
193​
194To create a route, create a new file that corresponds to the path of the route you want to create. For example:
195​
196| Path | Filename | Type |
197| ---------------- | ------------------- | -------------- |
198| `/` | `index.tsx` | Index Route |
199| `/about` | `about.tsx` | Static Route |
200| | `posts.tsx` | "Layout" Route |
201| `/posts/` | `posts/index.tsx` | Index Route |
202| `/posts/:postId` | `posts/$postId.tsx` | Dynamic Route |
203| `/rest/*` | `rest/$.tsx` | Wildcard Route |
204​
205## Defining Routes
206​
207To define a route, use the `createFileRoute` function to export the route as the `Route` variable.
208​
209For example, to handle the `/posts/:postId` route, you would create a file named `posts/$postId.tsx` here:
210​
211```
212src/
213β”œβ”€β”€ routes
214β”‚ β”œβ”€β”€ posts/$postId.tsx
215```
216​
217Then, define the route like this:
218​
219```tsx
220// src/routes/posts/$postId.tsx
221import { createFileRoute } from '@tanstack/react-router'
222​
223export const Route = createFileRoute('/posts/$postId')({
224 component: PostComponent,
225})
226```
227​
228> [!NOTE]
229> The path string passed to `createFileRoute` 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.
230​
231## This is just the "start"
232​
233This has been just a high-level overview of how to configure routes using TanStack Router. For more detailed information, please refer to the [TanStack Router documentation](/router/latest/docs/framework/react/routing/file-based-routing).