Skip to content

Commit d533f87

Browse files
feat(router-core): params.priority route option as tie breaker in matching algorithm (#7411)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
1 parent b3f2ab8 commit d533f87

7 files changed

Lines changed: 195 additions & 0 deletions

File tree

‎.changeset/kind-rivers-joke.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/router-core': minor
3+
---
4+
5+
params.priority route option as tie breaker in route matching algorithm

‎docs/router/api/router/RouteOptionsType.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,14 @@ The `RouteOptions` type accepts an object with the following properties:
8484
- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function returns parsed params, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
8585
- Experimental: returning `false` during incoming route matching skips this route and allows matching to continue to another candidate route.
8686

87+
### `params.priority` property
88+
89+
- Type: `number`
90+
- Optional
91+
- Defaults to `0`
92+
- Controls the matching order when multiple route candidates with `params.parse` can match the same URL segment. Higher numbers are tried first. If a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate.
93+
- This only affects competing candidates that use `params.parse`; normal route specificity still applies, so static routes continue to match before dynamic, optional, or wildcard routes.
94+
8795
### `params.stringify` method
8896

8997
- Type: `(params: TParams) => Record<string, string>`

‎docs/router/guide/path-params.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,29 @@ function PostComponent() {
131131

132132
<!-- ::end:framework -->
133133

134+
## Prioritizing Parsed Path Param Routes
135+
136+
When multiple dynamic, optional, or wildcard routes can match the same URL, routes with `params.parse` are tried before equivalent routes without it. If multiple matching candidates use `params.parse`, you can use `params.priority` to control which candidate is tried first.
137+
138+
Higher `params.priority` values are tried first. The default priority is `0`, and if a higher-priority route's `params.parse` returns `false`, matching continues to the next candidate route.
139+
140+
```tsx title="src/routes/posts.$postId.tsx"
141+
export const Route = createFileRoute('/posts/$postId')({
142+
params: {
143+
priority: 10,
144+
parse: ({ postId }) => {
145+
if (!/^\d+$/.test(postId)) return false
146+
return { postId: Number(postId) }
147+
},
148+
stringify: ({ postId }) => ({ postId: String(postId) }),
149+
},
150+
})
151+
```
152+
153+
With a fallback `/posts/$slug` route, `/posts/123` can match the parsed numeric route first, while `/posts/hello-world` can fall through to the slug route when `params.parse` returns `false`.
154+
155+
`params.priority` only affects competing candidates that use `params.parse`. It does not override normal route specificity, so static routes still match before dynamic, optional, or wildcard routes.
156+
134157
## Navigating with Path Params
135158

136159
When navigating to a route with path params, TypeScript will require you to pass the params either as an object or as a function that returns an object of params.

‎packages/router-core/src/new-process-route-tree.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -403,6 +403,7 @@ function parseSegments<TRouteLike extends RouteLike>(
403403
}
404404

405405
node.parse = parseParams ?? null
406+
node.priority = route.options?.params?.priority ?? 0
406407

407408
// make node "matchable"
408409
if (isLeaf && !node.route) {
@@ -430,16 +431,20 @@ function sortDynamic(
430431
suffix?: string
431432
caseSensitive: boolean
432433
parse: null | ((params: Record<string, string>) => unknown)
434+
priority: number
433435
},
434436
b: {
435437
prefix?: string
436438
suffix?: string
437439
caseSensitive: boolean
438440
parse: null | ((params: Record<string, string>) => unknown)
441+
priority: number
439442
},
440443
) {
441444
if (a.parse && !b.parse) return -1
442445
if (!a.parse && b.parse) return 1
446+
if (a.parse && b.parse && (a.priority || b.priority))
447+
return b.priority - a.priority
443448
if (a.prefix && b.prefix && a.prefix !== b.prefix) {
444449
if (a.prefix.startsWith(b.prefix)) return -1
445450
if (b.prefix.startsWith(a.prefix)) return 1
@@ -512,6 +517,7 @@ function createStaticNode<T extends RouteLike>(
512517
fullPath,
513518
parent: null,
514519
parse: null,
520+
priority: 0,
515521
}
516522
}
517523

@@ -543,6 +549,7 @@ function createDynamicNode<T extends RouteLike>(
543549
fullPath,
544550
parent: null,
545551
parse: null,
552+
priority: 0,
546553
caseSensitive,
547554
prefix,
548555
suffix,
@@ -605,6 +612,9 @@ type SegmentNode<T extends RouteLike> = {
605612

606613
/** route.options.params.parse function, set on the last node of the route */
607614
parse: null | ((params: Record<string, string>) => unknown)
615+
616+
/** route.options.params.priority ?? 0 */
617+
priority: number
608618
}
609619

610620
type RouteLike = {
@@ -618,6 +628,7 @@ type RouteLike = {
618628
parseParams?: (params: Record<string, string>) => unknown
619629
params?: {
620630
parse?: (params: Record<string, string>) => unknown
631+
priority?: number
621632
}
622633
}
623634
} &

‎packages/router-core/src/route.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,13 @@ export type StringifyParamsFn<in out TPath extends string, in out TParams> = (
188188
export type ParamsOptions<in out TPath extends string, in out TParams> = {
189189
params?: {
190190
parse?: ParseParamsFn<TPath, TParams> & ValidateParsedParams<TPath, TParams>
191+
/**
192+
* When multiple route candidates use `params.parse` during matching,
193+
* higher priorities are tried first.
194+
*
195+
* @default 0
196+
*/
197+
priority?: number
191198
stringify?: StringifyParamsFn<TPath, TParams>
192199
}
193200

‎packages/router-core/tests/match-params.test.ts‎

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ type TestRoute = {
1212
options?: {
1313
params?: {
1414
parse?: (params: Record<string, string>) => unknown
15+
priority?: number
1516
}
1617
}
1718
children?: Array<TestRoute>
@@ -266,6 +267,7 @@ describe('params.parse route selection', () => {
266267
options: {
267268
params: {
268269
parse: (params) => params,
270+
priority: 999,
269271
},
270272
},
271273
},
@@ -306,6 +308,138 @@ describe('params.parse route selection', () => {
306308
)
307309
})
308310

311+
it('params.priority breaks ties between params.parse routes', () => {
312+
const { processedTree } = processRouteTree(
313+
root([
314+
{
315+
id: '/$a',
316+
fullPath: '/$a',
317+
path: '$a',
318+
options: {
319+
params: {
320+
parse: (params) => params,
321+
priority: -1,
322+
},
323+
},
324+
},
325+
{
326+
id: '/$z',
327+
fullPath: '/$z',
328+
path: '$z',
329+
options: {
330+
params: {
331+
parse: (params) => params,
332+
priority: 1,
333+
},
334+
},
335+
},
336+
]),
337+
)
338+
339+
expect(findRouteMatch('/123', processedTree)?.route.id).toBe('/$z')
340+
})
341+
342+
it('treats missing params.priority as 0', () => {
343+
const priorityOneParse = vi.fn(() => false)
344+
const defaultPriorityParse = vi.fn((params: Record<string, string>) => {
345+
return params
346+
})
347+
const priorityNegativeOneParse = vi.fn(
348+
(params: Record<string, string>) => {
349+
return params
350+
},
351+
)
352+
353+
const { processedTree } = processRouteTree(
354+
root([
355+
{
356+
id: '/$default',
357+
fullPath: '/$default',
358+
path: '$default',
359+
options: {
360+
params: {
361+
parse: defaultPriorityParse,
362+
},
363+
},
364+
},
365+
{
366+
id: '/$low',
367+
fullPath: '/$low',
368+
path: '$low',
369+
options: {
370+
params: {
371+
parse: priorityNegativeOneParse,
372+
priority: -1,
373+
},
374+
},
375+
},
376+
{
377+
id: '/$high',
378+
fullPath: '/$high',
379+
path: '$high',
380+
options: {
381+
params: {
382+
parse: priorityOneParse,
383+
priority: 1,
384+
},
385+
},
386+
},
387+
]),
388+
)
389+
390+
expect(findRouteMatch('/123', processedTree)?.route.id).toBe('/$default')
391+
expect(priorityOneParse).toHaveBeenCalledWith({ high: '123' })
392+
expect(defaultPriorityParse).toHaveBeenCalledWith({ default: '123' })
393+
expect(priorityNegativeOneParse).toHaveBeenCalledWith({ low: '123' })
394+
expect(priorityOneParse.mock.invocationCallOrder[0]!).toBeLessThan(
395+
defaultPriorityParse.mock.invocationCallOrder[0]!,
396+
)
397+
expect(defaultPriorityParse.mock.invocationCallOrder[0]!).toBeLessThan(
398+
priorityNegativeOneParse.mock.invocationCallOrder[0]!,
399+
)
400+
})
401+
402+
it('falls through to the next params.parse route by params.priority', () => {
403+
const lowerPriorityParse = vi.fn((params: Record<string, string>) => {
404+
return params
405+
})
406+
const higherPriorityParse = vi.fn(() => false)
407+
408+
const { processedTree } = processRouteTree(
409+
root([
410+
{
411+
id: '/$number',
412+
fullPath: '/$number',
413+
path: '$number',
414+
options: {
415+
params: {
416+
parse: lowerPriorityParse,
417+
priority: 1,
418+
},
419+
},
420+
},
421+
{
422+
id: '/$uuid',
423+
fullPath: '/$uuid',
424+
path: '$uuid',
425+
options: {
426+
params: {
427+
parse: higherPriorityParse,
428+
priority: 10,
429+
},
430+
},
431+
},
432+
]),
433+
)
434+
435+
expect(findRouteMatch('/42', processedTree)?.route.id).toBe('/$number')
436+
expect(higherPriorityParse).toHaveBeenCalledWith({ uuid: '42' })
437+
expect(lowerPriorityParse).toHaveBeenCalledWith({ number: '42' })
438+
expect(higherPriorityParse.mock.invocationCallOrder[0]!).toBeLessThan(
439+
lowerPriorityParse.mock.invocationCallOrder[0]!,
440+
)
441+
})
442+
309443
it('declaration order breaks ties between params.parse routes', () => {
310444
const routeTree = root([
311445
{

‎packages/router-core/tests/new-process-route-tree.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1419,6 +1419,7 @@ describe('findRouteMatch', () => {
14191419
"parent": [Circular],
14201420
"parse": null,
14211421
"pathless": null,
1422+
"priority": 0,
14221423
"route": {
14231424
"fullPath": "/$foo/",
14241425
"id": "/$foo/_layout/",
@@ -1434,6 +1435,7 @@ describe('findRouteMatch', () => {
14341435
"parent": [Circular],
14351436
"parse": [Function],
14361437
"pathless": null,
1438+
"priority": 0,
14371439
"route": {
14381440
"children": [
14391441
{
@@ -1470,6 +1472,7 @@ describe('findRouteMatch', () => {
14701472
"parent": [Circular],
14711473
"parse": null,
14721474
"pathless": null,
1475+
"priority": 0,
14731476
"route": {
14741477
"fullPath": "/$foo/bar",
14751478
"id": "/$foo/_layout/bar",
@@ -1485,6 +1488,7 @@ describe('findRouteMatch', () => {
14851488
},
14861489
],
14871490
"prefix": undefined,
1491+
"priority": 0,
14881492
"route": null,
14891493
"static": null,
14901494
"staticInsensitive": Map {
@@ -1498,6 +1502,7 @@ describe('findRouteMatch', () => {
14981502
"parent": [Circular],
14991503
"parse": null,
15001504
"pathless": null,
1505+
"priority": 0,
15011506
"route": {
15021507
"fullPath": "/$foo/hello",
15031508
"id": "/$foo/hello",
@@ -1524,6 +1529,7 @@ describe('findRouteMatch', () => {
15241529
"parent": [Circular],
15251530
"parse": null,
15261531
"pathless": null,
1532+
"priority": 0,
15271533
"route": {
15281534
"fullPath": "/",
15291535
"id": "/",
@@ -1539,6 +1545,7 @@ describe('findRouteMatch', () => {
15391545
"parent": null,
15401546
"parse": null,
15411547
"pathless": null,
1548+
"priority": 0,
15421549
"route": null,
15431550
"static": null,
15441551
"staticInsensitive": null,

0 commit comments

Comments
 (0)