@tanstack/react-router 1.120.13 → 1.120.16

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