@tanstack/react-router 1.121.0-alpha.5 → 1.121.0

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.
@@ -0,0 +1,1951 @@
1
+ export default `# Code-Based Routing
2
+
3
+ > [!TIP]
4
+ > Code-based routing is not recommended for most applications. It is recommended to use [File-Based Routing](../file-based-routing.md) instead.
5
+
6
+ ## ⚠️ Before You Start
7
+
8
+ - If you're using [File-Based Routing](../file-based-routing.md), **skip this guide**.
9
+ - 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.
10
+
11
+ ## Route Trees
12
+
13
+ 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.
14
+
15
+ 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:
16
+
17
+ Here is the file-based version:
18
+
19
+ \`\`\`
20
+ routes/
21
+ ├── __root.tsx
22
+ ├── index.tsx
23
+ ├── about.tsx
24
+ ├── posts/
25
+ │ ├── index.tsx
26
+ │ ├── $postId.tsx
27
+ ├── posts.$postId.edit.tsx
28
+ ├── settings/
29
+ │ ├── profile.tsx
30
+ │ ├── notifications.tsx
31
+ ├── _pathlessLayout.tsx
32
+ ├── _pathlessLayout/
33
+ │ ├── route-a.tsx
34
+ ├── ├── route-b.tsx
35
+ ├── files/
36
+ │ ├── $.tsx
37
+ \`\`\`
38
+
39
+ And here is a summarized code-based version:
40
+
41
+ \`\`\`tsx
42
+ import { createRootRoute, createRoute } from '@tanstack/react-router'
43
+
44
+ const rootRoute = createRootRoute()
45
+
46
+ const indexRoute = createRoute({
47
+ getParentRoute: () => rootRoute,
48
+ path: '/',
49
+ })
50
+
51
+ const aboutRoute = createRoute({
52
+ getParentRoute: () => rootRoute,
53
+ path: 'about',
54
+ })
55
+
56
+ const postsRoute = createRoute({
57
+ getParentRoute: () => rootRoute,
58
+ path: 'posts',
59
+ })
60
+
61
+ const postsIndexRoute = createRoute({
62
+ getParentRoute: () => postsRoute,
63
+ path: '/',
64
+ })
65
+
66
+ const postRoute = createRoute({
67
+ getParentRoute: () => postsRoute,
68
+ path: '$postId',
69
+ })
70
+
71
+ const postEditorRoute = createRoute({
72
+ getParentRoute: () => rootRoute,
73
+ path: 'posts/$postId/edit',
74
+ })
75
+
76
+ const settingsRoute = createRoute({
77
+ getParentRoute: () => rootRoute,
78
+ path: 'settings',
79
+ })
80
+
81
+ const profileRoute = createRoute({
82
+ getParentRoute: () => settingsRoute,
83
+ path: 'profile',
84
+ })
85
+
86
+ const notificationsRoute = createRoute({
87
+ getParentRoute: () => settingsRoute,
88
+ path: 'notifications',
89
+ })
90
+
91
+ const pathlessLayoutRoute = createRoute({
92
+ getParentRoute: () => rootRoute,
93
+ id: 'pathlessLayout',
94
+ })
95
+
96
+ const pathlessLayoutARoute = createRoute({
97
+ getParentRoute: () => pathlessLayoutRoute,
98
+ path: 'route-a',
99
+ })
100
+
101
+ const pathlessLayoutBRoute = createRoute({
102
+ getParentRoute: () => pathlessLayoutRoute,
103
+ path: 'route-b',
104
+ })
105
+
106
+ const filesRoute = createRoute({
107
+ getParentRoute: () => rootRoute,
108
+ path: 'files/$',
109
+ })
110
+ \`\`\`
111
+
112
+ ## Anatomy of a Route
113
+
114
+ All other routes other than the root route are configured using the \`createRoute\` function:
115
+
116
+ \`\`\`tsx
117
+ const route = createRoute({
118
+ getParentRoute: () => rootRoute,
119
+ path: '/posts',
120
+ component: PostsComponent,
121
+ })
122
+ \`\`\`
123
+
124
+ The \`getParentRoute\` option is a function that returns the parent route of the route you're creating.
125
+
126
+ **❓❓❓ "Wait, you're making me pass the parent route for every route I make?"**
127
+
128
+ 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!
129
+
130
+ > [!IMPORTANT]
131
+ > 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.
132
+
133
+ 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:
134
+
135
+ | Path | Normalized Path |
136
+ | -------- | --------------- |
137
+ | \`/\` | \`/\` |
138
+ | \`/about\` | \`about\` |
139
+ | \`about/\` | \`about\` |
140
+ | \`about\` | \`about\` |
141
+ | \`$\` | \`$\` |
142
+ | \`/$\` | \`$\` |
143
+ | \`/$/\` | \`$\` |
144
+
145
+ ## Manually building the route tree
146
+
147
+ 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.
148
+
149
+ \`\`\`tsx
150
+ /* prettier-ignore */
151
+ const routeTree = rootRoute.addChildren([
152
+ indexRoute,
153
+ aboutRoute,
154
+ postsRoute.addChildren([
155
+ postsIndexRoute,
156
+ postRoute,
157
+ ]),
158
+ postEditorRoute,
159
+ settingsRoute.addChildren([
160
+ profileRoute,
161
+ notificationsRoute,
162
+ ]),
163
+ pathlessLayoutRoute.addChildren([
164
+ pathlessLayoutARoute,
165
+ pathlessLayoutBRoute,
166
+ ]),
167
+ filesRoute.addChildren([
168
+ fileRoute,
169
+ ]),
170
+ ])
171
+ /* prettier-ignore-end */
172
+ \`\`\`
173
+
174
+ But before you can go ahead and build the route tree, you need to understand how the Routing Concepts for Code-Based Routing work.
175
+
176
+ ## Routing Concepts for Code-Based Routing
177
+
178
+ 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.
179
+
180
+ We're going to assume you've read the [Routing Concepts](../routing-concepts.md) guide and are familiar with each of these main concepts:
181
+
182
+ - The Root Route
183
+ - Basic Routes
184
+ - Index Routes
185
+ - Dynamic Route Segments
186
+ - Splat / Catch-All Routes
187
+ - Layout Routes
188
+ - Pathless Routes
189
+ - Non-Nested Routes
190
+
191
+ Now, let's take a look at how to create each of these route types in code.
192
+
193
+ ## The Root Route
194
+
195
+ Creating a root route in code-based routing is thankfully the same as doing so in file-based routing. Call the \`createRootRoute()\` function.
196
+
197
+ 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).
198
+
199
+ \`\`\`tsx
200
+ // Standard root route
201
+ import { createRootRoute } from '@tanstack/react-router'
202
+
203
+ const rootRoute = createRootRoute()
204
+
205
+ // Root route with Context
206
+ import { createRootRouteWithContext } from '@tanstack/react-router'
207
+ import type { QueryClient } from '@tanstack/react-query'
208
+
209
+ export interface MyRouterContext {
210
+ queryClient: QueryClient
211
+ }
212
+ const rootRoute = createRootRouteWithContext<MyRouterContext>()
213
+ \`\`\`
214
+
215
+ To learn more about Context in TanStack Router, see the [Router Context](../../guide/router-context.md) guide.
216
+
217
+ ## Basic Routes
218
+
219
+ To create a basic route, simply provide a normal \`path\` string to the \`createRoute\` function:
220
+
221
+ \`\`\`tsx
222
+ const aboutRoute = createRoute({
223
+ getParentRoute: () => rootRoute,
224
+ path: 'about',
225
+ })
226
+ \`\`\`
227
+
228
+ See, it's that simple! The \`aboutRoute\` will match the URL \`/about\`.
229
+
230
+ ## Index Routes
231
+
232
+ 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:
233
+
234
+ \`\`\`tsx
235
+ const postsRoute = createRoute({
236
+ getParentRoute: () => rootRoute,
237
+ path: 'posts',
238
+ })
239
+
240
+ const postsIndexRoute = createRoute({
241
+ getParentRoute: () => postsRoute,
242
+ // Notice the single slash \`/\` here
243
+ path: '/',
244
+ })
245
+ \`\`\`
246
+
247
+ So, the \`postsIndexRoute\` will match the URL \`/posts/\` (or \`/posts\`).
248
+
249
+ ## Dynamic Route Segments
250
+
251
+ 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\`:
252
+
253
+ \`\`\`tsx
254
+ const postIdRoute = createRoute({
255
+ getParentRoute: () => postsRoute,
256
+ path: '$postId',
257
+ // In a loader
258
+ loader: ({ params }) => fetchPost(params.postId),
259
+ // Or in a component
260
+ component: PostComponent,
261
+ })
262
+
263
+ function PostComponent() {
264
+ const { postId } = postIdRoute.useParams()
265
+ return <div>Post ID: {postId}</div>
266
+ }
267
+ \`\`\`
268
+
269
+ > [!TIP]
270
+ > 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.
271
+
272
+ ## Splat / Catch-All Routes
273
+
274
+ 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:
275
+
276
+ \`\`\`tsx
277
+ const filesRoute = createRoute({
278
+ getParentRoute: () => rootRoute,
279
+ path: 'files',
280
+ })
281
+
282
+ const fileRoute = createRoute({
283
+ getParentRoute: () => filesRoute,
284
+ path: '$',
285
+ })
286
+ \`\`\`
287
+
288
+ For the URL \`/documents/hello-world\`, the \`params\` object will look like this:
289
+
290
+ \`\`\`js
291
+ {
292
+ '_splat': 'documents/hello-world'
293
+ }
294
+ \`\`\`
295
+
296
+ ## Layout Routes
297
+
298
+ 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:
299
+
300
+ \`\`\`tsx
301
+ const postsRoute = createRoute({
302
+ getParentRoute: () => rootRoute,
303
+ path: 'posts',
304
+ component: PostsLayoutComponent, // The layout component
305
+ })
306
+
307
+ function PostsLayoutComponent() {
308
+ return (
309
+ <div>
310
+ <h1>Posts</h1>
311
+ <Outlet />
312
+ </div>
313
+ )
314
+ }
315
+
316
+ const postsIndexRoute = createRoute({
317
+ getParentRoute: () => postsRoute,
318
+ path: '/',
319
+ })
320
+
321
+ const postsCreateRoute = createRoute({
322
+ getParentRoute: () => postsRoute,
323
+ path: 'create',
324
+ })
325
+
326
+ const routeTree = rootRoute.addChildren([
327
+ // The postsRoute is the layout route
328
+ // Its children will be nested under the PostsLayoutComponent
329
+ postsRoute.addChildren([postsIndexRoute, postsCreateRoute]),
330
+ ])
331
+ \`\`\`
332
+
333
+ Now, both the \`postsIndexRoute\` and \`postsCreateRoute\` will render their contents inside of the \`PostsLayoutComponent\`:
334
+
335
+ \`\`\`tsx
336
+ // URL: /posts
337
+ <PostsLayoutComponent>
338
+ <PostsIndexComponent />
339
+ </PostsLayoutComponent>
340
+
341
+ // URL: /posts/create
342
+ <PostsLayoutComponent>
343
+ <PostsCreateComponent />
344
+ </PostsLayoutComponent>
345
+ \`\`\`
346
+
347
+ ## Pathless Layout Routes
348
+
349
+ 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.
350
+
351
+ \`\`\`tsx
352
+ const pathlessLayoutRoute = createRoute({
353
+ getParentRoute: () => rootRoute,
354
+ id: 'pathlessLayout',
355
+ component: PathlessLayoutComponent,
356
+ })
357
+
358
+ function PathlessLayoutComponent() {
359
+ return (
360
+ <div>
361
+ <h1>Pathless Layout</h1>
362
+ <Outlet />
363
+ </div>
364
+ )
365
+ }
366
+
367
+ const pathlessLayoutARoute = createRoute({
368
+ getParentRoute: () => pathlessLayoutRoute,
369
+ path: 'route-a',
370
+ })
371
+
372
+ const pathlessLayoutBRoute = createRoute({
373
+ getParentRoute: () => pathlessLayoutRoute,
374
+ path: 'route-b',
375
+ })
376
+
377
+ const routeTree = rootRoute.addChildren([
378
+ // The pathless layout route has no path, only an id
379
+ // So its children will be nested under the pathless layout route
380
+ pathlessLayoutRoute.addChildren([pathlessLayoutARoute, pathlessLayoutBRoute]),
381
+ ])
382
+ \`\`\`
383
+
384
+ Now both \`/route-a\` and \`/route-b\` will render their contents inside of the \`PathlessLayoutComponent\`:
385
+
386
+ \`\`\`tsx
387
+ // URL: /route-a
388
+ <PathlessLayoutComponent>
389
+ <RouteAComponent />
390
+ </PathlessLayoutComponent>
391
+
392
+ // URL: /route-b
393
+ <PathlessLayoutComponent>
394
+ <RouteBComponent />
395
+ </PathlessLayoutComponent>
396
+ \`\`\`
397
+
398
+ ## Non-Nested Routes
399
+
400
+ 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:
401
+
402
+ - \`/posts_/$postId/edit\`
403
+ - \`/posts\`
404
+ - \`$postId\`
405
+
406
+ 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):
407
+
408
+ \`\`\`tsx
409
+ // The posts editor route is nested under the root route
410
+ const postEditorRoute = createRoute({
411
+ getParentRoute: () => rootRoute,
412
+ // The path includes the entire path we need to match
413
+ path: 'posts/$postId/edit',
414
+ })
415
+
416
+ const postsRoute = createRoute({
417
+ getParentRoute: () => rootRoute,
418
+ path: 'posts',
419
+ })
420
+
421
+ const postRoute = createRoute({
422
+ getParentRoute: () => postsRoute,
423
+ path: '$postId',
424
+ })
425
+
426
+ const routeTree = rootRoute.addChildren([
427
+ // The post editor route is nested under the root route
428
+ postEditorRoute,
429
+ postsRoute.addChildren([postRoute]),
430
+ ])
431
+ \`\`\`
432
+
433
+ # File-Based Routing
434
+
435
+ 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.
436
+
437
+ ## What is File-Based Routing?
438
+
439
+ 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:
440
+
441
+ - **Simplicity**: File-based routing is visually intuitive and easy to understand for both new and experienced developers.
442
+ - **Organization**: Routes are organized in a way that mirrors the URL structure of your application.
443
+ - **Scalability**: As your application grows, file-based routing makes it easy to add new routes and maintain existing ones.
444
+ - **Code-Splitting**: File-based routing allows TanStack Router to automatically code-split your routes for better performance.
445
+ - **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.
446
+ - **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.
447
+
448
+ ## \`/\`s or \`.\`s?
449
+
450
+ 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!
451
+
452
+ ## Directory Routes
453
+
454
+ 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.
455
+
456
+ See the example below:
457
+
458
+ | Filename | Route Path | Component Output |
459
+ | ----------------------- | ------------------------- | --------------------------------- |
460
+ | ʦ \`__root.tsx\` | | \`<Root>\` |
461
+ | ʦ \`index.tsx\` | \`/\` (exact) | \`<Root><RootIndex>\` |
462
+ | ʦ \`about.tsx\` | \`/about\` | \`<Root><About>\` |
463
+ | ʦ \`posts.tsx\` | \`/posts\` | \`<Root><Posts>\` |
464
+ | 📂 \`posts\` | | |
465
+ | ┄ ʦ \`index.tsx\` | \`/posts\` (exact) | \`<Root><Posts><PostsIndex>\` |
466
+ | ┄ ʦ \`$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
467
+ | 📂 \`posts_\` | | |
468
+ | ┄ 📂 \`$postId\` | | |
469
+ | ┄ ┄ ʦ \`edit.tsx\` | \`/posts/$postId/edit\` | \`<Root><EditPost>\` |
470
+ | ʦ \`settings.tsx\` | \`/settings\` | \`<Root><Settings>\` |
471
+ | 📂 \`settings\` | | \`<Root><Settings>\` |
472
+ | ┄ ʦ \`profile.tsx\` | \`/settings/profile\` | \`<Root><Settings><Profile>\` |
473
+ | ┄ ʦ \`notifications.tsx\` | \`/settings/notifications\` | \`<Root><Settings><Notifications>\` |
474
+ | ʦ \`_pathlessLayout.tsx\` | | \`<Root><PathlessLayout>\` |
475
+ | 📂 \`_pathlessLayout\` | | |
476
+ | ┄ ʦ \`route-a.tsx\` | \`/route-a\` | \`<Root><PathlessLayout><RouteA>\` |
477
+ | ┄ ʦ \`route-b.tsx\` | \`/route-b\` | \`<Root><PathlessLayout><RouteB>\` |
478
+ | 📂 \`files\` | | |
479
+ | ┄ ʦ \`$.tsx\` | \`/files/$\` | \`<Root><Files>\` |
480
+ | 📂 \`account\` | | |
481
+ | ┄ ʦ \`route.tsx\` | \`/account\` | \`<Root><Account>\` |
482
+ | ┄ ʦ \`overview.tsx\` | \`/account/overview\` | \`<Root><Account><Overview>\` |
483
+
484
+ ## Flat Routes
485
+
486
+ Flat routing gives you the ability to use \`.\`s to denote route nesting levels.
487
+
488
+ This can be useful when you have a large number of uniquely deeply nested routes and want to avoid creating directories for each one:
489
+
490
+ See the example below:
491
+
492
+ | Filename | Route Path | Component Output |
493
+ | ------------------------------- | ------------------------- | --------------------------------- |
494
+ | ʦ \`__root.tsx\` | | \`<Root>\` |
495
+ | ʦ \`index.tsx\` | \`/\` (exact) | \`<Root><RootIndex>\` |
496
+ | ʦ \`about.tsx\` | \`/about\` | \`<Root><About>\` |
497
+ | ʦ \`posts.tsx\` | \`/posts\` | \`<Root><Posts>\` |
498
+ | ʦ \`posts.index.tsx\` | \`/posts\` (exact) | \`<Root><Posts><PostsIndex>\` |
499
+ | ʦ \`posts.$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
500
+ | ʦ \`posts_.$postId.edit.tsx\` | \`/posts/$postId/edit\` | \`<Root><EditPost>\` |
501
+ | ʦ \`settings.tsx\` | \`/settings\` | \`<Root><Settings>\` |
502
+ | ʦ \`settings.profile.tsx\` | \`/settings/profile\` | \`<Root><Settings><Profile>\` |
503
+ | ʦ \`settings.notifications.tsx\` | \`/settings/notifications\` | \`<Root><Settings><Notifications>\` |
504
+ | ʦ \`_pathlessLayout.tsx\` | | \`<Root><PathlessLayout>\` |
505
+ | ʦ \`_pathlessLayout.route-a.tsx\` | \`/route-a\` | \`<Root><PathlessLayout><RouteA>\` |
506
+ | ʦ \`_pathlessLayout.route-b.tsx\` | \`/route-b\` | \`<Root><PathlessLayout><RouteB>\` |
507
+ | ʦ \`files.$.tsx\` | \`/files/$\` | \`<Root><Files>\` |
508
+ | ʦ \`account.tsx\` | \`/account\` | \`<Root><Account>\` |
509
+ | ʦ \`account.overview.tsx\` | \`/account/overview\` | \`<Root><Account><Overview>\` |
510
+
511
+ ## Mixed Flat and Directory Routes
512
+
513
+ 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:
514
+
515
+ See the example below:
516
+
517
+ | Filename | Route Path | Component Output |
518
+ | ------------------------------ | ------------------------- | --------------------------------- |
519
+ | ʦ \`__root.tsx\` | | \`<Root>\` |
520
+ | ʦ \`index.tsx\` | \`/\` (exact) | \`<Root><RootIndex>\` |
521
+ | ʦ \`about.tsx\` | \`/about\` | \`<Root><About>\` |
522
+ | ʦ \`posts.tsx\` | \`/posts\` | \`<Root><Posts>\` |
523
+ | 📂 \`posts\` | | |
524
+ | ┄ ʦ \`index.tsx\` | \`/posts\` (exact) | \`<Root><Posts><PostsIndex>\` |
525
+ | ┄ ʦ \`$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
526
+ | ┄ ʦ \`$postId.edit.tsx\` | \`/posts/$postId/edit\` | \`<Root><Posts><Post><EditPost>\` |
527
+ | ʦ \`settings.tsx\` | \`/settings\` | \`<Root><Settings>\` |
528
+ | ʦ \`settings.profile.tsx\` | \`/settings/profile\` | \`<Root><Settings><Profile>\` |
529
+ | ʦ \`settings.notifications.tsx\` | \`/settings/notifications\` | \`<Root><Settings><Notifications>\` |
530
+ | ʦ \`account.tsx\` | \`/account\` | \`<Root><Account>\` |
531
+ | ʦ \`account.overview.tsx\` | \`/account/overview\` | \`<Root><Account><Overview>\` |
532
+
533
+ 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.
534
+
535
+ > [!TIP]
536
+ > 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.
537
+
538
+ ## Getting started with File-Based Routing
539
+
540
+ 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.
541
+
542
+ 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.
543
+
544
+ [//]: # 'SupportedBundlersList'
545
+
546
+ - [Installation with Vite](../installation-with-vite.md)
547
+ - [Installation with Rspack/Rsbuild](../installation-with-rspack.md)
548
+ - [Installation with Webpack](../installation-with-webpack.md)
549
+ - [Installation with Esbuild](../installation-with-esbuild.md)
550
+
551
+ [//]: # 'SupportedBundlersList'
552
+
553
+ 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.
554
+
555
+ 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.
556
+
557
+ # File Naming Conventions
558
+
559
+ 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.
560
+
561
+ | Feature | Description |
562
+ | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
563
+ | **\`__root.tsx\`** | The root route file must be named \`__root.tsx\` and must be placed in the root of the configured \`routesDirectory\`. |
564
+ | **\`.\` Separator** | Routes can use the \`.\` character to denote a nested route. For example, \`blog.post\` will be generated as a child of \`blog\`. |
565
+ | **\`$\` Token** | Route segments with the \`$\` token are parameterized and will extract the value from the URL pathname as a route \`param\`. |
566
+ | **\`_\` 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. |
567
+ | **\`_\` Suffix** | Route segments with the \`_\` suffix exclude the route from being nested under any parent routes. |
568
+ | **\`-\` 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. |
569
+ | **\`(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. |
570
+ | **\`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). |
571
+ | **\`.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). |
572
+
573
+ > **💡 Remember:** The file-naming conventions for your project could be affected by what [options](../../../../api/file-based-routing.md) are configured.
574
+
575
+ ## Dynamic Path Params
576
+
577
+ 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:
578
+
579
+ | Filename | Route Path | Component Output |
580
+ | --------------------- | ---------------- | --------------------- |
581
+ | ... | ... | ... |
582
+ | ʦ \`posts.$postId.tsx\` | \`/posts/$postId\` | \`<Root><Posts><Post>\` |
583
+
584
+ We'll learn more about dynamic path params in the [Path Params](../../guide/path-params.md) guide.
585
+
586
+ ## Pathless Routes
587
+
588
+ 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:
589
+
590
+ | Filename | Route Path | Component Output |
591
+ | -------------- | ---------- | ---------------- |
592
+ | ʦ \`_app.tsx\` | | |
593
+ | ʦ \`_app.a.tsx\` | /a | \`<Root><App><A>\` |
594
+ | ʦ \`_app.b.tsx\` | /b | \`<Root><App><B>\` |
595
+
596
+ To learn more about pathless routes, see the [Routing Concepts - Pathless Routes](../routing-concepts.md#pathless-layout-routes) guide.
597
+
598
+ # Installation with Vite
599
+
600
+ [//]: # 'BundlerConfiguration'
601
+
602
+ To use file-based routing with **Esbuild**, you'll need to install the \`@tanstack/router-plugin\` package.
603
+
604
+ \`\`\`sh
605
+ npm install -D @tanstack/router-plugin
606
+ \`\`\`
607
+
608
+ Once installed, you'll need to add the plugin to your configuration.
609
+
610
+ \`\`\`tsx
611
+ // esbuild.config.js
612
+ import { tanstackRouter } from '@tanstack/router-plugin/esbuild'
613
+
614
+ export default {
615
+ // ...
616
+ plugins: [
617
+ tanstackRouter({
618
+ target: 'react',
619
+ autoCodeSplitting: true,
620
+ verboseFileRoutes: false,
621
+ }),
622
+ ],
623
+ }
624
+ \`\`\`
625
+
626
+ Or, you can clone our [Quickstart Esbuild example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-esbuild-file-based) and get started.
627
+
628
+ Now that you've added the plugin to your Esbuild configuration, you're all set to start using file-based routing with TanStack Router.
629
+
630
+ [//]: # 'BundlerConfiguration'
631
+
632
+ ## Ignoring the generated route tree file
633
+
634
+ 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.
635
+
636
+ Here are some resources to help you ignore the generated route tree file:
637
+
638
+ - Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
639
+ - ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
640
+ - Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
641
+
642
+ > [!WARNING]
643
+ > If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
644
+
645
+ 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:
646
+
647
+ \`\`\`json
648
+ {
649
+ "files.readonlyInclude": {
650
+ "**/routeTree.gen.ts": true
651
+ },
652
+ "files.watcherExclude": {
653
+ "**/routeTree.gen.ts": true
654
+ },
655
+ "search.exclude": {
656
+ "**/routeTree.gen.ts": true
657
+ }
658
+ }
659
+ \`\`\`
660
+
661
+ 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.
662
+
663
+ ## Configuration
664
+
665
+ When using the TanStack Router Plugin with Esbuild for File-based routing, it comes with some sane defaults that should work for most projects:
666
+
667
+ \`\`\`json
668
+ {
669
+ "routesDirectory": "./src/routes",
670
+ "generatedRouteTree": "./src/routeTree.gen.ts",
671
+ "routeFileIgnorePrefix": "-",
672
+ "quoteStyle": "single"
673
+ }
674
+ \`\`\`
675
+
676
+ 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.
677
+
678
+ You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
679
+
680
+ # Installation with Router CLI
681
+
682
+ > [!WARNING]
683
+ > 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.
684
+
685
+ To use file-based routing with the TanStack Router CLI, you'll need to install the \`@tanstack/router-cli\` package.
686
+
687
+ \`\`\`sh
688
+ npm install -D @tanstack/router-cli
689
+ \`\`\`
690
+
691
+ Once installed, you'll need to amend your your scripts in your \`package.json\` for the CLI to \`watch\` and \`generate\` files.
692
+
693
+ \`\`\`json
694
+ {
695
+ "scripts": {
696
+ "generate-routes": "tsr generate",
697
+ "watch-routes": "tsr watch",
698
+ "build": "npm run generate-routes && ...",
699
+ "dev": "npm run watch-routes && ..."
700
+ }
701
+ }
702
+ \`\`\`
703
+
704
+ [//]: # 'AfterScripts'
705
+ [//]: # 'AfterScripts'
706
+
707
+ 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.
708
+
709
+ With the CLI installed, the following commands are made available via the \`tsr\` command
710
+
711
+ ## Using the \`generate\` command
712
+
713
+ Generates the routes for a project based on the provided configuration.
714
+
715
+ \`\`\`sh
716
+ tsr generate
717
+ \`\`\`
718
+
719
+ ## Using the \`watch\` command
720
+
721
+ Continuously watches the specified directories and regenerates routes as needed.
722
+
723
+ **Usage:**
724
+
725
+ \`\`\`sh
726
+ tsr watch
727
+ \`\`\`
728
+
729
+ 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.
730
+
731
+ ## Ignoring the generated route tree file
732
+
733
+ 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.
734
+
735
+ Here are some resources to help you ignore the generated route tree file:
736
+
737
+ - Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
738
+ - ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
739
+ - Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
740
+
741
+ > [!WARNING]
742
+ > If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
743
+
744
+ 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:
745
+
746
+ \`\`\`json
747
+ {
748
+ "files.readonlyInclude": {
749
+ "**/routeTree.gen.ts": true
750
+ },
751
+ "files.watcherExclude": {
752
+ "**/routeTree.gen.ts": true
753
+ },
754
+ "search.exclude": {
755
+ "**/routeTree.gen.ts": true
756
+ }
757
+ }
758
+ \`\`\`
759
+
760
+ 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.
761
+
762
+ ## Configuration
763
+
764
+ When using the TanStack Router CLI for File-based routing, it comes with some sane defaults that should work for most projects:
765
+
766
+ \`\`\`json
767
+ {
768
+ "routesDirectory": "./src/routes",
769
+ "generatedRouteTree": "./src/routeTree.gen.ts",
770
+ "routeFileIgnorePrefix": "-",
771
+ "quoteStyle": "single"
772
+ }
773
+ \`\`\`
774
+
775
+ 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.
776
+
777
+ [//]: # 'TargetConfiguration'
778
+ [//]: # 'TargetConfiguration'
779
+
780
+ You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
781
+
782
+ # Installation with Rspack
783
+
784
+ [//]: # 'BundlerConfiguration'
785
+
786
+ To use file-based routing with **Rspack** or **Rsbuild**, you'll need to install the \`@tanstack/router-plugin\` package.
787
+
788
+ \`\`\`sh
789
+ npm install -D @tanstack/router-plugin
790
+ \`\`\`
791
+
792
+ Once installed, you'll need to add the plugin to your configuration.
793
+
794
+ \`\`\`tsx
795
+ // rsbuild.config.ts
796
+ import { defineConfig } from '@rsbuild/core'
797
+ import { pluginReact } from '@rsbuild/plugin-react'
798
+ import { tanstackRouter } from '@tanstack/router-plugin/rspack'
799
+
800
+ export default defineConfig({
801
+ plugins: [pluginReact()],
802
+ tools: {
803
+ rspack: {
804
+ plugins: [
805
+ tanstackRouter({
806
+ target: 'react',
807
+ autoCodeSplitting: true,
808
+ verboseFileRoutes: false,
809
+ }),
810
+ ],
811
+ },
812
+ },
813
+ })
814
+ \`\`\`
815
+
816
+ 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.
817
+
818
+ 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.
819
+
820
+ [//]: # 'BundlerConfiguration'
821
+
822
+ ## Ignoring the generated route tree file
823
+
824
+ 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.
825
+
826
+ Here are some resources to help you ignore the generated route tree file:
827
+
828
+ - Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
829
+ - ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
830
+ - Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
831
+
832
+ > [!WARNING]
833
+ > If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
834
+
835
+ 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:
836
+
837
+ \`\`\`json
838
+ {
839
+ "files.readonlyInclude": {
840
+ "**/routeTree.gen.ts": true
841
+ },
842
+ "files.watcherExclude": {
843
+ "**/routeTree.gen.ts": true
844
+ },
845
+ "search.exclude": {
846
+ "**/routeTree.gen.ts": true
847
+ }
848
+ }
849
+ \`\`\`
850
+
851
+ 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.
852
+
853
+ ## Configuration
854
+
855
+ 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:
856
+
857
+ \`\`\`json
858
+ {
859
+ "routesDirectory": "./src/routes",
860
+ "generatedRouteTree": "./src/routeTree.gen.ts",
861
+ "routeFileIgnorePrefix": "-",
862
+ "quoteStyle": "single"
863
+ }
864
+ \`\`\`
865
+
866
+ 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.
867
+
868
+ You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
869
+
870
+ # Installation with Vite
871
+
872
+ [//]: # 'BundlerConfiguration'
873
+
874
+ To use file-based routing with **Vite**, you'll need to install the \`@tanstack/router-plugin\` package.
875
+
876
+ \`\`\`sh
877
+ npm install -D @tanstack/router-plugin
878
+ \`\`\`
879
+
880
+ Once installed, you'll need to add the plugin to your Vite configuration.
881
+
882
+ \`\`\`ts
883
+ // vite.config.ts
884
+ import { defineConfig } from 'vite'
885
+ import react from '@vitejs/plugin-react'
886
+ import { tanstackRouter } from '@tanstack/router-plugin/vite'
887
+
888
+ // https://vitejs.dev/config/
889
+ export default defineConfig({
890
+ plugins: [
891
+ // Please make sure that '@tanstack/router-plugin' is passed before '@vitejs/plugin-react'
892
+ tanstackRouter({
893
+ target: 'react',
894
+ autoCodeSplitting: true,
895
+ verboseFileRoutes: false,
896
+ }),
897
+ react(),
898
+ // ...
899
+ ],
900
+ })
901
+ \`\`\`
902
+
903
+ Or, you can clone our [Quickstart Vite example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-file-based) and get started.
904
+
905
+ > [!WARNING]
906
+ > 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.
907
+
908
+ Now that you've added the plugin to your Vite configuration, you're all set to start using file-based routing with TanStack Router.
909
+
910
+ [//]: # 'BundlerConfiguration'
911
+
912
+ ## Ignoring the generated route tree file
913
+
914
+ 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.
915
+
916
+ Here are some resources to help you ignore the generated route tree file:
917
+
918
+ - Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
919
+ - ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
920
+ - Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
921
+
922
+ > [!WARNING]
923
+ > If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
924
+
925
+ 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:
926
+
927
+ \`\`\`json
928
+ {
929
+ "files.readonlyInclude": {
930
+ "**/routeTree.gen.ts": true
931
+ },
932
+ "files.watcherExclude": {
933
+ "**/routeTree.gen.ts": true
934
+ },
935
+ "search.exclude": {
936
+ "**/routeTree.gen.ts": true
937
+ }
938
+ }
939
+ \`\`\`
940
+
941
+ 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.
942
+
943
+ ## Configuration
944
+
945
+ When using the TanStack Router Plugin with Vite for File-based routing, it comes with some sane defaults that should work for most projects:
946
+
947
+ \`\`\`json
948
+ {
949
+ "routesDirectory": "./src/routes",
950
+ "generatedRouteTree": "./src/routeTree.gen.ts",
951
+ "routeFileIgnorePrefix": "-",
952
+ "quoteStyle": "single"
953
+ }
954
+ \`\`\`
955
+
956
+ 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.
957
+
958
+ You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
959
+
960
+ # Installation with Webpack
961
+
962
+ [//]: # 'BundlerConfiguration'
963
+
964
+ To use file-based routing with **Webpack**, you'll need to install the \`@tanstack/router-plugin\` package.
965
+
966
+ \`\`\`sh
967
+ npm install -D @tanstack/router-plugin
968
+ \`\`\`
969
+
970
+ Once installed, you'll need to add the plugin to your configuration.
971
+
972
+ \`\`\`tsx
973
+ // webpack.config.ts
974
+ import { tanstackRouter } from '@tanstack/router-plugin/webpack'
975
+
976
+ export default {
977
+ plugins: [
978
+ tanstackRouter({
979
+ target: 'react',
980
+ autoCodeSplitting: true,
981
+ verboseFileRoutes: false,
982
+ }),
983
+ ],
984
+ }
985
+ \`\`\`
986
+
987
+ Or, you can clone our [Quickstart Webpack example](https://github.com/TanStack/router/tree/main/examples/react/quickstart-webpack-file-based) and get started.
988
+
989
+ Now that you've added the plugin to your Webpack configuration, you're all set to start using file-based routing with TanStack Router.
990
+
991
+ [//]: # 'BundlerConfiguration'
992
+
993
+ ## Ignoring the generated route tree file
994
+
995
+ 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.
996
+
997
+ Here are some resources to help you ignore the generated route tree file:
998
+
999
+ - Prettier - [https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore](https://prettier.io/docs/en/ignore.html#ignoring-files-prettierignore)
1000
+ - ESLint - [https://eslint.org/docs/latest/use/configure/ignore#ignoring-files](https://eslint.org/docs/latest/use/configure/ignore#ignoring-files)
1001
+ - Biome - [https://biomejs.dev/reference/configuration/#filesignore](https://biomejs.dev/reference/configuration/#filesignore)
1002
+
1003
+ > [!WARNING]
1004
+ > If you are using VSCode, you may experience the route tree file unexpectedly open (with errors) after renaming a route.
1005
+
1006
+ 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:
1007
+
1008
+ \`\`\`json
1009
+ {
1010
+ "files.readonlyInclude": {
1011
+ "**/routeTree.gen.ts": true
1012
+ },
1013
+ "files.watcherExclude": {
1014
+ "**/routeTree.gen.ts": true
1015
+ },
1016
+ "search.exclude": {
1017
+ "**/routeTree.gen.ts": true
1018
+ }
1019
+ }
1020
+ \`\`\`
1021
+
1022
+ 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.
1023
+
1024
+ ## Configuration
1025
+
1026
+ When using the TanStack Router Plugin with Webpack for File-based routing, it comes with some sane defaults that should work for most projects:
1027
+
1028
+ \`\`\`json
1029
+ {
1030
+ "routesDirectory": "./src/routes",
1031
+ "generatedRouteTree": "./src/routeTree.gen.ts",
1032
+ "routeFileIgnorePrefix": "-",
1033
+ "quoteStyle": "single"
1034
+ }
1035
+ \`\`\`
1036
+
1037
+ 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.
1038
+
1039
+ You can find all the available configuration options in the [File-based Routing API Reference](../../../../api/file-based-routing.md).
1040
+
1041
+ # Route Matching
1042
+
1043
+ Route matching follows a consistent and predictable pattern. This guide will explain how route trees are matched.
1044
+
1045
+ 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:
1046
+
1047
+ - Index Route
1048
+ - Static Routes (most specific to least specific)
1049
+ - Dynamic Routes (longest to shortest)
1050
+ - Splat/Wildcard Routes
1051
+
1052
+ Consider the following pseudo route tree:
1053
+
1054
+ \`\`\`
1055
+ Root
1056
+ - blog
1057
+ - $postId
1058
+ - /
1059
+ - new
1060
+ - /
1061
+ - *
1062
+ - about
1063
+ - about/us
1064
+ \`\`\`
1065
+
1066
+ After sorting, this route tree will become:
1067
+
1068
+ \`\`\`
1069
+ Root
1070
+ - /
1071
+ - about/us
1072
+ - about
1073
+ - blog
1074
+ - /
1075
+ - new
1076
+ - $postId
1077
+ - *
1078
+ \`\`\`
1079
+
1080
+ This final order represents the order in which routes will be matched based on specificity.
1081
+
1082
+ Using that route tree, let's follow the matching process for a few different URLs:
1083
+
1084
+ - \`/blog\`
1085
+ \`\`\`
1086
+ Root
1087
+ ❌ /
1088
+ ❌ about/us
1089
+ ❌ about
1090
+ ⏩ blog
1091
+ ✅ /
1092
+ - new
1093
+ - $postId
1094
+ - *
1095
+ \`\`\`
1096
+ - \`/blog/my-post\`
1097
+ \`\`\`
1098
+ Root
1099
+ ❌ /
1100
+ ❌ about/us
1101
+ ❌ about
1102
+ ⏩ blog
1103
+ ❌ /
1104
+ ❌ new
1105
+ ✅ $postId
1106
+ - *
1107
+ \`\`\`
1108
+ - \`/\`
1109
+ \`\`\`
1110
+ Root
1111
+ ✅ /
1112
+ - about/us
1113
+ - about
1114
+ - blog
1115
+ - /
1116
+ - new
1117
+ - $postId
1118
+ - *
1119
+ \`\`\`
1120
+ - \`/not-a-route\`
1121
+ \`\`\`
1122
+ Root
1123
+ ❌ /
1124
+ ❌ about/us
1125
+ ❌ about
1126
+ ❌ blog
1127
+ - /
1128
+ - new
1129
+ - $postId
1130
+ ✅ *
1131
+ \`\`\`
1132
+
1133
+ # Route Trees
1134
+
1135
+ TanStack Router uses a nested route tree to match up the URL with the correct component tree to render.
1136
+
1137
+ To build a route tree, TanStack Router supports:
1138
+
1139
+ - [File-Based Routing](../file-based-routing.md)
1140
+ - [Code-Based Routing](../code-based-routing.md)
1141
+
1142
+ 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.
1143
+
1144
+ ## Route Trees
1145
+
1146
+ 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:
1147
+
1148
+ \`\`\`tsx
1149
+ ├── blog
1150
+ │ ├── posts
1151
+ │ │ ├── $postId
1152
+ \`\`\`
1153
+
1154
+ And render a component tree that looks like this:
1155
+
1156
+ \`\`\`tsx
1157
+ <Blog>
1158
+ <Posts>
1159
+ <Post postId="123" />
1160
+ </Posts>
1161
+ </Blog>
1162
+ \`\`\`
1163
+
1164
+ Let's take that concept and expand it out to a larger site structure, but with file-names now:
1165
+
1166
+ \`\`\`
1167
+ /routes
1168
+ ├── __root.tsx
1169
+ ├── index.tsx
1170
+ ├── about.tsx
1171
+ ├── posts/
1172
+ │ ├── index.tsx
1173
+ │ ├── $postId.tsx
1174
+ ├── posts.$postId.edit.tsx
1175
+ ├── settings/
1176
+ │ ├── profile.tsx
1177
+ │ ├── notifications.tsx
1178
+ ├── _pathlessLayout/
1179
+ │ ├── route-a.tsx
1180
+ ├── ├── route-b.tsx
1181
+ ├── files/
1182
+ │ ├── $.tsx
1183
+ \`\`\`
1184
+
1185
+ 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.
1186
+
1187
+ ## Route Tree Configuration
1188
+
1189
+ Route trees can be configured using a few different ways:
1190
+
1191
+ - [Flat Routes](../file-based-routing.md#flat-routes)
1192
+ - [Directories](../file-based-routing.md#directory-routes)
1193
+ - [Mixed Flat Routes and Directories](../file-based-routing.md#mixed-flat-and-directory-routes)
1194
+ - [Virtual File Routes](../virtual-file-routes.md)
1195
+ - [Code-Based Routes](../code-based-routing.md)
1196
+
1197
+ 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.
1198
+
1199
+ # Routing Concepts
1200
+
1201
+ TanStack Router supports a number of powerful routing concepts that allow you to build complex and dynamic routing systems with ease.
1202
+
1203
+ Each of these concepts is useful and powerful, and we'll dive into each of them in the following sections.
1204
+
1205
+ ## Anatomy of a Route
1206
+
1207
+ All 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:
1208
+
1209
+ \`\`\`tsx
1210
+ import { createFileRoute } from '@tanstack/react-router'
1211
+
1212
+ export const Route = createFileRoute({
1213
+ component: PostsComponent,
1214
+ })
1215
+ \`\`\`
1216
+
1217
+ The \`createFileRoute\` function takes a single argument, the file-route's path as a string.
1218
+
1219
+ **❓❓❓ "Wait, you're making me pass the path of the route file to \`createFileRoute\`?"**
1220
+
1221
+ Yes! 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.
1222
+
1223
+ The 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 🤷‍♂️)
1224
+
1225
+ ## The Root Route
1226
+
1227
+ The root route is the top-most route in the entire tree and encapsulates all other routes as children.
1228
+
1229
+ - It has no path
1230
+ - It is **always** matched
1231
+ - Its \`component\` is **always** rendered
1232
+
1233
+ Even though it doesn't have a path, the root route has access to all of the same functionality as other routes including:
1234
+
1235
+ - components
1236
+ - loaders
1237
+ - search param validation
1238
+ - etc.
1239
+
1240
+ To create a root route, call the \`createRootRoute()\` function and export it as the \`Route\` variable in your route file:
1241
+
1242
+ \`\`\`tsx
1243
+ // Standard root route
1244
+ import { createRootRoute } from '@tanstack/react-router'
1245
+
1246
+ export const Route = createRootRoute()
1247
+
1248
+ // Root route with Context
1249
+ import { createRootRouteWithContext } from '@tanstack/react-router'
1250
+ import type { QueryClient } from '@tanstack/react-query'
1251
+
1252
+ export interface MyRouterContext {
1253
+ queryClient: QueryClient
1254
+ }
1255
+ export const Route = createRootRouteWithContext<MyRouterContext>()
1256
+ \`\`\`
1257
+
1258
+ To learn more about Context in TanStack Router, see the [Router Context](../../guide/router-context.md) guide.
1259
+
1260
+ ## Basic Routes
1261
+
1262
+ Basic routes match a specific path, for example \`/about\`, \`/settings\`, \`/settings/notifications\` are all basic routes, as they match the path exactly.
1263
+
1264
+ Let's take a look at an \`/about\` route:
1265
+
1266
+ \`\`\`tsx
1267
+ // about.tsx
1268
+ import { createFileRoute } from '@tanstack/react-router'
1269
+
1270
+ export const Route = createFileRoute({
1271
+ component: AboutComponent,
1272
+ })
1273
+
1274
+ function AboutComponent() {
1275
+ return <div>About</div>
1276
+ }
1277
+ \`\`\`
1278
+
1279
+ Basic routes are simple and straightforward. They match the path exactly and render the provided component.
1280
+
1281
+ ## Index Routes
1282
+
1283
+ Index routes specifically target their parent route when it is **matched exactly and no child route is matched**.
1284
+
1285
+ Let's take a look at an index route for a \`/posts\` URL:
1286
+
1287
+ \`\`\`tsx
1288
+ // posts.index.tsx
1289
+ import { createFileRoute } from '@tanstack/react-router'
1290
+
1291
+ // Note the trailing slash, which is used to target index routes
1292
+ export const Route = createFileRoute({
1293
+ component: PostsIndexComponent,
1294
+ })
1295
+
1296
+ function PostsIndexComponent() {
1297
+ return <div>Please select a post!</div>
1298
+ }
1299
+ \`\`\`
1300
+
1301
+ This route will be matched when the URL is \`/posts\` exactly.
1302
+
1303
+ ## Dynamic Route Segments
1304
+
1305
+ Route 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' }\`.
1306
+
1307
+ These params are then usable in your route's configuration and components! Let's look at a \`posts.$postId.tsx\` route:
1308
+
1309
+ \`\`\`tsx
1310
+ import { createFileRoute } from '@tanstack/react-router'
1311
+
1312
+ export const Route = createFileRoute({
1313
+ // In a loader
1314
+ loader: ({ params }) => fetchPost(params.postId),
1315
+ // Or in a component
1316
+ component: PostComponent,
1317
+ })
1318
+
1319
+ function PostComponent() {
1320
+ // In a component!
1321
+ const { postId } = Route.useParams()
1322
+ return <div>Post ID: {postId}</div>
1323
+ }
1324
+ \`\`\`
1325
+
1326
+ > 🧠 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.
1327
+
1328
+ ## Splat / Catch-All Routes
1329
+
1330
+ A 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.
1331
+
1332
+ For 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:
1333
+
1334
+ \`\`\`js
1335
+ {
1336
+ '_splat': 'documents/hello-world'
1337
+ }
1338
+ \`\`\`
1339
+
1340
+ > ⚠️ 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.
1341
+
1342
+ > 🧠 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.
1343
+
1344
+ ## Layout Routes
1345
+
1346
+ Layout routes are used to wrap child routes with additional components and logic. They are useful for:
1347
+
1348
+ - Wrapping child routes with a layout component
1349
+ - Enforcing a \`loader\` requirement before displaying any child routes
1350
+ - Validating and providing search params to child routes
1351
+ - Providing fallbacks for error components or pending elements to child routes
1352
+ - Providing shared context to all child routes
1353
+ - And more!
1354
+
1355
+ Let's take a look at an example layout route called \`app.tsx\`:
1356
+
1357
+ \`\`\`
1358
+ routes/
1359
+ ├── app.tsx
1360
+ ├── app.dashboard.tsx
1361
+ ├── app.settings.tsx
1362
+ \`\`\`
1363
+
1364
+ In the tree above, \`app.tsx\` is a layout route that wraps two child routes, \`app.dashboard.tsx\` and \`app.settings.tsx\`.
1365
+
1366
+ This tree structure is used to wrap the child routes with a layout component:
1367
+
1368
+ \`\`\`tsx
1369
+ import { Outlet, createFileRoute } from '@tanstack/react-router'
1370
+
1371
+ export const Route = createFileRoute({
1372
+ component: AppLayoutComponent,
1373
+ })
1374
+
1375
+ function AppLayoutComponent() {
1376
+ return (
1377
+ <div>
1378
+ <h1>App Layout</h1>
1379
+ <Outlet />
1380
+ </div>
1381
+ )
1382
+ }
1383
+ \`\`\`
1384
+
1385
+ The following table shows which component(s) will be rendered based on the URL:
1386
+
1387
+ | URL Path | Component |
1388
+ | ---------------- | ------------------------ |
1389
+ | \`/\` | \`<Index>\` |
1390
+ | \`/app/dashboard\` | \`<AppLayout><Dashboard>\` |
1391
+ | \`/app/settings\` | \`<AppLayout><Settings>\` |
1392
+
1393
+ Since TanStack Router supports mixed flat and directory routes, you can also express your application's routing using layout routes within directories:
1394
+
1395
+ \`\`\`
1396
+ routes/
1397
+ ├── app/
1398
+ │ ├── route.tsx
1399
+ │ ├── dashboard.tsx
1400
+ │ ├── settings.tsx
1401
+ \`\`\`
1402
+
1403
+ In 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\`.
1404
+
1405
+ Layout Routes also let you enforce component and loader logic for Dynamic Route Segments:
1406
+
1407
+ \`\`\`
1408
+ routes/
1409
+ ├── app/users/
1410
+ │ ├── $userId/
1411
+ | | ├── route.tsx
1412
+ | | ├── index.tsx
1413
+ | | ├── edit.tsx
1414
+ \`\`\`
1415
+
1416
+ ## Pathless Layout Routes
1417
+
1418
+ Like [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.
1419
+
1420
+ Pathless Layout Routes are prefixed with an underscore (\`_\`) to denote that they are "pathless".
1421
+
1422
+ > 🧠 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.
1423
+
1424
+ Let's take a look at an example route called \`_pathlessLayout.tsx\`:
1425
+
1426
+ \`\`\`
1427
+
1428
+ routes/
1429
+ ├── _pathlessLayout.tsx
1430
+ ├── _pathlessLayout.a.tsx
1431
+ ├── _pathlessLayout.b.tsx
1432
+
1433
+ \`\`\`
1434
+
1435
+ In the tree above, \`_pathlessLayout.tsx\` is a pathless layout route that wraps two child routes, \`_pathlessLayout.a.tsx\` and \`_pathlessLayout.b.tsx\`.
1436
+
1437
+ The \`_pathlessLayout.tsx\` route is used to wrap the child routes with a Pathless layout component:
1438
+
1439
+ \`\`\`tsx
1440
+ import { Outlet, createFileRoute } from '@tanstack/react-router'
1441
+
1442
+ export const Route = createFileRoute({
1443
+ component: PathlessLayoutComponent,
1444
+ })
1445
+
1446
+ function PathlessLayoutComponent() {
1447
+ return (
1448
+ <div>
1449
+ <h1>Pathless layout</h1>
1450
+ <Outlet />
1451
+ </div>
1452
+ )
1453
+ }
1454
+ \`\`\`
1455
+
1456
+ The following table shows which component will be rendered based on the URL:
1457
+
1458
+ | URL Path | Component |
1459
+ | -------- | --------------------- |
1460
+ | \`/\` | \`<Index>\` |
1461
+ | \`/a\` | \`<PathlessLayout><A>\` |
1462
+ | \`/b\` | \`<PathlessLayout><B>\` |
1463
+
1464
+ Since TanStack Router supports mixed flat and directory routes, you can also express your application's routing using pathless layout routes within directories:
1465
+
1466
+ \`\`\`
1467
+ routes/
1468
+ ├── _pathlessLayout/
1469
+ │ ├── route.tsx
1470
+ │ ├── a.tsx
1471
+ │ ├── b.tsx
1472
+ \`\`\`
1473
+
1474
+ However, 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.
1475
+
1476
+ This means that you cannot do this:
1477
+
1478
+ \`\`\`
1479
+ routes/
1480
+ ├── _$postId/ ❌
1481
+ │ ├── ...
1482
+ \`\`\`
1483
+
1484
+ Rather, you'd have to do this:
1485
+
1486
+ \`\`\`
1487
+ routes/
1488
+ ├── $postId/
1489
+ ├── _postPathlessLayout/ ✅
1490
+ │ ├── ...
1491
+ \`\`\`
1492
+
1493
+ ## Non-Nested Routes
1494
+
1495
+ Non-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.
1496
+
1497
+ Consider the following flat route tree:
1498
+
1499
+ \`\`\`
1500
+ routes/
1501
+ ├── posts.tsx
1502
+ ├── posts.$postId.tsx
1503
+ ├── posts_.$postId.edit.tsx
1504
+ \`\`\`
1505
+
1506
+ The following table shows which component will be rendered based on the URL:
1507
+
1508
+ | URL Path | Component |
1509
+ | ----------------- | ---------------------------- |
1510
+ | \`/posts\` | \`<Posts>\` |
1511
+ | \`/posts/123\` | \`<Posts><Post postId="123">\` |
1512
+ | \`/posts/123/edit\` | \`<PostEditor postId="123">\` |
1513
+
1514
+ - The \`posts.$postId.tsx\` route is nested as normal under the \`posts.tsx\` route and will render \`<Posts><Post>\`.
1515
+ - 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>\`.
1516
+
1517
+ ## Excluding Files and Folders from Routes
1518
+
1519
+ 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.
1520
+
1521
+ Consider the following route tree:
1522
+
1523
+ \`\`\`
1524
+ routes/
1525
+ ├── posts.tsx
1526
+ ├── -posts-table.tsx // 👈🏼 ignored
1527
+ ├── -components/ // 👈🏼 ignored
1528
+ │ ├── header.tsx // 👈🏼 ignored
1529
+ │ ├── footer.tsx // 👈🏼 ignored
1530
+ │ ├── ...
1531
+ \`\`\`
1532
+
1533
+ We can import from the excluded files into our posts route
1534
+
1535
+ \`\`\`tsx
1536
+ import { createFileRoute } from '@tanstack/react-router'
1537
+ import { PostsTable } from './-posts-table'
1538
+ import { PostsHeader } from './-components/header'
1539
+ import { PostsFooter } from './-components/footer'
1540
+
1541
+ export const Route = createFileRoute('/posts')({
1542
+ loader: () => fetchPosts(),
1543
+ component: PostComponent,
1544
+ })
1545
+
1546
+ function PostComponent() {
1547
+ const posts = Route.useLoaderData()
1548
+
1549
+ return (
1550
+ <div>
1551
+ <PostsHeader />
1552
+ <PostsTable posts={posts} />
1553
+ <PostsFooter />
1554
+ </div>
1555
+ )
1556
+ }
1557
+ \`\`\`
1558
+
1559
+ The excluded files will not be added to \`routeTree.gen.ts\`.
1560
+
1561
+ ## Pathless Route Group Directories
1562
+
1563
+ Pathless 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.
1564
+
1565
+ \`\`\`
1566
+ routes/
1567
+ ├── index.tsx
1568
+ ├── (app)/
1569
+ │ ├── dashboard.tsx
1570
+ │ ├── settings.tsx
1571
+ │ ├── users.tsx
1572
+ ├── (auth)/
1573
+ │ ├── login.tsx
1574
+ │ ├── register.tsx
1575
+ \`\`\`
1576
+
1577
+ In 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.
1578
+
1579
+ The following table shows which component will be rendered based on the URL:
1580
+
1581
+ | URL Path | Component |
1582
+ | ------------ | ------------- |
1583
+ | \`/\` | \`<Index>\` |
1584
+ | \`/dashboard\` | \`<Dashboard>\` |
1585
+ | \`/settings\` | \`<Settings>\` |
1586
+ | \`/users\` | \`<Users>\` |
1587
+ | \`/login\` | \`<Login>\` |
1588
+ | \`/register\` | \`<Register>\` |
1589
+
1590
+ As you can see, the \`app\` and \`auth\` directories are purely organizational and do not affect the route tree or component tree in any way.
1591
+
1592
+ # Virtual File Routes
1593
+
1594
+ > 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.
1595
+
1596
+ Virtual 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:
1597
+
1598
+ - You have an existing route organization that you want to keep.
1599
+ - You want to customize the location of your route files.
1600
+ - You want to completely override TanStack Router's file-based route generation and build your own convention.
1601
+
1602
+ Here's a quick example of using virtual file routes to map a route tree to a set of real files in your project:
1603
+
1604
+ \`\`\`tsx
1605
+ // routes.ts
1606
+ import {
1607
+ rootRoute,
1608
+ route,
1609
+ index,
1610
+ layout,
1611
+ physical,
1612
+ } from '@tanstack/virtual-file-routes'
1613
+
1614
+ export const routes = rootRoute('root.tsx', [
1615
+ index('index.tsx'),
1616
+ layout('pathlessLayout.tsx', [
1617
+ route('/dashboard', 'app/dashboard.tsx', [
1618
+ index('app/dashboard-index.tsx'),
1619
+ route('/invoices', 'app/dashboard-invoices.tsx', [
1620
+ index('app/invoices-index.tsx'),
1621
+ route('$id', 'app/invoice-detail.tsx'),
1622
+ ]),
1623
+ ]),
1624
+ physical('/posts', 'posts'),
1625
+ ]),
1626
+ ])
1627
+ \`\`\`
1628
+
1629
+ ## Configuration
1630
+
1631
+ Virtual file routes can be configured either via:
1632
+
1633
+ - The \`TanStackRouter\` plugin for Vite/Rspack/Webpack
1634
+ - The \`tsr.config.json\` file for the TanStack Router CLI
1635
+
1636
+ ## Configuration via the TanStackRouter Plugin
1637
+
1638
+ If 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:
1639
+
1640
+ \`\`\`tsx
1641
+ // vite.config.ts
1642
+ import { defineConfig } from 'vite'
1643
+ import react from '@vitejs/plugin-react'
1644
+ import { tanstackRouter } from '@tanstack/router-plugin/vite'
1645
+
1646
+ export default defineConfig({
1647
+ plugins: [
1648
+ tanstackRouter({
1649
+ target: 'react',
1650
+ verboseFileRoutes: false,
1651
+ virtualRouteConfig: './routes.ts',
1652
+ }),
1653
+ react(),
1654
+ ],
1655
+ })
1656
+ \`\`\`
1657
+
1658
+ Or, you choose to define the virtual routes directly in the configuration:
1659
+
1660
+ \`\`\`tsx
1661
+ // vite.config.ts
1662
+ import { defineConfig } from 'vite'
1663
+ import react from '@vitejs/plugin-react'
1664
+ import { tanstackRouter } from '@tanstack/router-plugin/vite'
1665
+ import { rootRoute } from '@tanstack/virtual-file-routes'
1666
+
1667
+ const routes = rootRoute('root.tsx', [
1668
+ // ... the rest of your virtual route tree
1669
+ ])
1670
+
1671
+ export default defineConfig({
1672
+ plugins: [tanstackRouter({ virtualRouteConfig: routes }), react()],
1673
+ })
1674
+ \`\`\`
1675
+
1676
+ ## Creating Virtual File Routes
1677
+
1678
+ To 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:
1679
+
1680
+ - \`rootRoute\` - Creates a virtual root route.
1681
+ - \`route\` - Creates a virtual route.
1682
+ - \`index\` - Creates a virtual index route.
1683
+ - \`layout\` - Creates a virtual pathless layout route.
1684
+ - \`physical\` - Creates a physical virtual route (more on this later).
1685
+
1686
+ ## Virtual Root Route
1687
+
1688
+ The \`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:
1689
+
1690
+ \`\`\`tsx
1691
+ // routes.ts
1692
+ import { rootRoute } from '@tanstack/virtual-file-routes'
1693
+
1694
+ export const routes = rootRoute('root.tsx', [
1695
+ // ... children routes
1696
+ ])
1697
+ \`\`\`
1698
+
1699
+ ## Virtual Route
1700
+
1701
+ The \`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:
1702
+
1703
+ \`\`\`tsx
1704
+ // routes.ts
1705
+ import { route } from '@tanstack/virtual-file-routes'
1706
+
1707
+ export const routes = rootRoute('root.tsx', [
1708
+ route('/about', 'about.tsx', [
1709
+ // ... children routes
1710
+ ]),
1711
+ ])
1712
+ \`\`\`
1713
+
1714
+ You can also define a virtual route without a file name. This allows to set a common path prefix for its children:
1715
+
1716
+ \`\`\`tsx
1717
+ // routes.ts
1718
+ import { route } from '@tanstack/virtual-file-routes'
1719
+
1720
+ export const routes = rootRoute('root.tsx', [
1721
+ route('/hello', [
1722
+ route('/world', 'world.tsx'), // full path will be "/hello/world"
1723
+ route('/universe', 'universe.tsx'), // full path will be "/hello/universe"
1724
+ ]),
1725
+ ])
1726
+ \`\`\`
1727
+
1728
+ ## Virtual Index Route
1729
+
1730
+ The \`index\` function is used to create a virtual index route. It takes a file name. Here's an example of a virtual index route:
1731
+
1732
+ \`\`\`tsx
1733
+ import { index } from '@tanstack/virtual-file-routes'
1734
+
1735
+ const routes = rootRoute('root.tsx', [index('index.tsx')])
1736
+ \`\`\`
1737
+
1738
+ ## Virtual Pathless Route
1739
+
1740
+ The \`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:
1741
+
1742
+ \`\`\`tsx
1743
+ // routes.ts
1744
+ import { layout } from '@tanstack/virtual-file-routes'
1745
+
1746
+ export const routes = rootRoute('root.tsx', [
1747
+ layout('pathlessLayout.tsx', [
1748
+ // ... children routes
1749
+ ]),
1750
+ ])
1751
+ \`\`\`
1752
+
1753
+ You can also specify a pathless ID to give the route a unique identifier that is different from the filename:
1754
+
1755
+ \`\`\`tsx
1756
+ // routes.ts
1757
+ import { layout } from '@tanstack/virtual-file-routes'
1758
+
1759
+ export const routes = rootRoute('root.tsx', [
1760
+ layout('my-pathless-layout-id', 'pathlessLayout.tsx', [
1761
+ // ... children routes
1762
+ ]),
1763
+ ])
1764
+ \`\`\`
1765
+
1766
+ ## Physical Virtual Routes
1767
+
1768
+ Physical 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.
1769
+
1770
+ Consider the following file structure:
1771
+
1772
+ \`\`\`
1773
+ /routes
1774
+ ├── root.tsx
1775
+ ├── index.tsx
1776
+ ├── pathless.tsx
1777
+ ├── app
1778
+ │ ├── dashboard.tsx
1779
+ │ ├── dashboard-index.tsx
1780
+ │ ├── dashboard-invoices.tsx
1781
+ │ ├── invoices-index.tsx
1782
+ │ ├── invoice-detail.tsx
1783
+ └── posts
1784
+ ├── index.tsx
1785
+ ├── $postId.tsx
1786
+ ├── $postId.edit.tsx
1787
+ ├── comments/
1788
+ │ ├── index.tsx
1789
+ │ ├── $commentId.tsx
1790
+ └── likes/
1791
+ ├── index.tsx
1792
+ ├── $likeId.tsx
1793
+ \`\`\`
1794
+
1795
+ Let'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:
1796
+
1797
+ \`\`\`tsx
1798
+ // routes.ts
1799
+ export const routes = rootRoute('root.tsx', [
1800
+ // Set up your virtual routes as normal
1801
+ index('index.tsx'),
1802
+ layout('pathlessLayout.tsx', [
1803
+ route('/dashboard', 'app/dashboard.tsx', [
1804
+ index('app/dashboard-index.tsx'),
1805
+ route('/invoices', 'app/dashboard-invoices.tsx', [
1806
+ index('app/invoices-index.tsx'),
1807
+ route('$id', 'app/invoice-detail.tsx'),
1808
+ ]),
1809
+ ]),
1810
+ // Mount the \`posts\` directory under the \`/posts\` path
1811
+ physical('/posts', 'posts'),
1812
+ ]),
1813
+ ])
1814
+ \`\`\`
1815
+
1816
+ ## Virtual Routes inside of TanStack Router File Based routing
1817
+
1818
+ The previous section showed you how you can use TanStack Router's File Based routing convention inside of a virtual route configuration.
1819
+ However, the opposite is possible as well.
1820
+ You 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.
1821
+
1822
+ Consider the following file structure:
1823
+
1824
+ \`\`\`
1825
+ /routes
1826
+ ├── __root.tsx
1827
+ ├── foo
1828
+ │ ├── bar
1829
+ │ │ ├── __virtual.ts
1830
+ │ │ ├── details.tsx
1831
+ │ │ ├── home.tsx
1832
+ │ │ └── route.ts
1833
+ │ └── bar.tsx
1834
+ └── index.tsx
1835
+ \`\`\`
1836
+
1837
+ Let'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).
1838
+
1839
+ \`__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:
1840
+
1841
+ \`\`\`tsx
1842
+ // routes/foo/bar/__virtual.ts
1843
+ import {
1844
+ defineVirtualSubtreeConfig,
1845
+ index,
1846
+ route,
1847
+ } from '@tanstack/virtual-file-routes'
1848
+
1849
+ export default defineVirtualSubtreeConfig([
1850
+ index('home.tsx'),
1851
+ route('$id', 'details.tsx'),
1852
+ ])
1853
+ \`\`\`
1854
+
1855
+ The 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
1856
+
1857
+ - a subtree config object
1858
+ - a function returning a subtree config object
1859
+ - an async function returning a subtree config object
1860
+
1861
+ ## Inception
1862
+
1863
+ You can mix and match TanStack Router's File Based routing convention and virtual route configuration however you like.
1864
+ Let's go deeper!
1865
+ Check 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\`.
1866
+
1867
+ \`\`\`
1868
+ ├── __root.tsx
1869
+ ├── index.tsx
1870
+ ├── posts
1871
+ │ ├── __virtual.ts
1872
+ │ ├── details.tsx
1873
+ │ ├── home.tsx
1874
+ │ └── lets-go
1875
+ │ ├── deeper
1876
+ │ │ ├── __virtual.ts
1877
+ │ │ └── home.tsx
1878
+ │ └── index.tsx
1879
+ └── posts.tsx
1880
+ \`\`\`
1881
+
1882
+ ## Configuration via the TanStack Router CLI
1883
+
1884
+ If 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:
1885
+
1886
+ \`\`\`json
1887
+ // tsr.config.json
1888
+ {
1889
+ "virtualRouteConfig": "./routes.ts"
1890
+ }
1891
+ \`\`\`
1892
+
1893
+ Or 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:
1894
+
1895
+ \`\`\`json
1896
+ // tsr.config.json
1897
+ {
1898
+ "virtualRouteConfig": {
1899
+ "type": "root",
1900
+ "file": "root.tsx",
1901
+ "children": [
1902
+ {
1903
+ "type": "index",
1904
+ "file": "home.tsx"
1905
+ },
1906
+ {
1907
+ "type": "route",
1908
+ "file": "posts/posts.tsx",
1909
+ "path": "/posts",
1910
+ "children": [
1911
+ {
1912
+ "type": "index",
1913
+ "file": "posts/posts-home.tsx"
1914
+ },
1915
+ {
1916
+ "type": "route",
1917
+ "file": "posts/posts-detail.tsx",
1918
+ "path": "$postId"
1919
+ }
1920
+ ]
1921
+ },
1922
+ {
1923
+ "type": "layout",
1924
+ "id": "first",
1925
+ "file": "layout/first-pathless-layout.tsx",
1926
+ "children": [
1927
+ {
1928
+ "type": "layout",
1929
+ "id": "second",
1930
+ "file": "layout/second-pathless-layout.tsx",
1931
+ "children": [
1932
+ {
1933
+ "type": "route",
1934
+ "file": "a.tsx",
1935
+ "path": "/route-a"
1936
+ },
1937
+ {
1938
+ "type": "route",
1939
+ "file": "b.tsx",
1940
+ "path": "/route-b"
1941
+ }
1942
+ ]
1943
+ }
1944
+ ]
1945
+ }
1946
+ ]
1947
+ }
1948
+ }
1949
+ \`\`\`
1950
+
1951
+ `;