Skip to content

Commit 45c4ad8

Browse files
fix(router-core): lane match loader rewrite (TanStack#7805)
* fix: lane match loader rewrite --------- Co-authored-by: Manuel Schiller <[email protected]>
1 parent 65ae78c commit 45c4ad8

279 files changed

Lines changed: 28223 additions & 8503 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
---
2+
'@tanstack/router-core': patch
3+
'@tanstack/react-router': patch
4+
'@tanstack/solid-router': patch
5+
'@tanstack/vue-router': patch
6+
---
7+
8+
Rewrite match loading around a lane-based scheduler that tracks each navigation, preload, and background reload as an ordered unit of work. This fixes pending/redirect/retry state leaking between overlapping navigations, restores correct SSR status codes for redirects, errors, and not-found responses, and closes hydration gaps where the client re-ran work the server had already completed.
9+
10+
- Invalidation now retires matching active preloads so older speculative loader results cannot become fresh cache data after invalidation.
11+
- Route `headers()` now only runs on the server, matching the documented behavior — it is no longer invoked during client-side asset projection.
12+
- Default `gcTime` and `preloadGcTime` are reduced from 30 minutes (`1_800_000`) to 5 minutes (`300_000`).
13+
14+
**Removed / changed public API**
15+
16+
- `RouterState` no longer includes `loadedAt`, `isTransitioning`, `statusCode`, or `redirect`. Use `match.updatedAt` in place of `loadedAt`; subscribe to `router.state.status` / `router.state.isLoading` in place of `isTransitioning`; server response status and redirect handling are now internal to the server loader and are no longer exposed on `router.state`.
17+
- `RouteMatch.fetchCount` has been removed, with no replacement — it was purely informational.
18+
- `RouteMatch.status` no longer includes `'redirected'` (it remains `'pending' | 'success' | 'error' | 'notFound'`) — redirected matches are dropped from the match list instead of being rendered.
19+
- `RouteMatch.globalNotFound` has been renamed and privatized to the internal `_notFound` field. Use `match.status === 'notFound'` instead.
20+
- Removed `RouterCore` members `getMatch()`, `updateMatch()`, `cancelMatch()`, and `cancelMatches()` — read matches from `router.state.matches` (e.g. `router.state.matches.find((m) => m.id === id)`); there is no replacement for mutating or cancelling an individual in-flight match from outside the router.
21+
- Removed `hasNotFoundMatch()` — use `router.state.matches.some((m) => m.status === 'notFound')`.
22+
- Removed `looseRoutesById` — use `routesById`.
23+
- Removed `isPrerendering()`, `isViewTransitionTypesSupported`, and `viewTransitionPromise`, with no replacement.
24+
- Removed `getParsedLocationHref()` and `clearExpiredCache()`, with no replacement — expired cache entries are now reconciled automatically as part of match commit.
25+
- Removed `latestLoadPromise` and `beforeLoad()`, with no replacement.
26+
- `commitLocationPromise` and `pendingBuiltLocation` are now private (`_commitPromise`, `_pendingLocation`) and no longer part of the public `RouterCore` surface.
27+
- Removed the exported `GetMatchFn` and `UpdateMatchFn` types, along with the methods they typed.
28+
- Removed the standalone `getMatchedRoutes()` export from `@tanstack/router-core` — use the `router.getMatchedRoutes()` instance method instead.
29+
- `MatchRoutesOpts.preload` and `MatchRoutesOpts.dest` have been removed.
30+
- `StartTransitionFn` is now `(fn, expected, urgent?) => Promise<boolean>` (previously `(fn) => void`). This only affects custom framework adapters that implement `startTransition`.

‎benchmarks/memory/client/scenarios/interrupted-navigations/shared.ts‎

Lines changed: 0 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,6 @@ type RenderedEvent = {
3535
}
3636

3737
type InterruptedNavigationRouter = {
38-
latestLoadPromise: Promise<void> | undefined
3938
load: () => Promise<void>
4039
navigate: (options: {
4140
to: '/fast/$id' | '/slow/$id'
@@ -104,18 +103,6 @@ function assertSlowNavigationSettlement(settlement: NavigationSettlement) {
104103
)
105104
}
106105

107-
async function awaitExpectedLoadSettlement(loadPromise: Promise<void>) {
108-
try {
109-
await loadPromise
110-
} catch (reason) {
111-
if (reasonHasAbortShape(reason) || reasonHasCancellationShape(reason)) {
112-
return
113-
}
114-
115-
throw reason
116-
}
117-
}
118-
119106
function reasonHasAbortShape(reason: unknown) {
120107
return reason instanceof DOMException && reason.name === 'AbortError'
121108
}
@@ -144,7 +131,6 @@ export function createWorkload(
144131
let navigateFast: (id: string) => Promise<void> = uninitialized
145132
let startSlowNavigation: (id: string) => Promise<NavigationSettlement> =
146133
uninitializedSettlement
147-
let getLatestLoadPromise: () => Promise<void> | undefined = () => undefined
148134

149135
function assertRenderedPage(page: 'shell' | 'fast', id?: string) {
150136
const element = container?.querySelector<HTMLElement>('[data-bench-page]')
@@ -203,7 +189,6 @@ export function createWorkload(
203189
const mounted = mountTestApp(container)
204190
const router = mounted.router as InterruptedNavigationRouter
205191
unmount = mounted.unmount
206-
getLatestLoadPromise = () => router.latestLoadPromise
207192

208193
unsub = router.subscribe('onRendered', (event) => {
209194
if (
@@ -265,7 +250,6 @@ export function createWorkload(
265250
expectedRenderedPath = undefined
266251
navigateFast = uninitialized
267252
startSlowNavigation = uninitializedSettlement
268-
getLatestLoadPromise = () => undefined
269253
}
270254

271255
async function interrupt(
@@ -276,12 +260,6 @@ export function createWorkload(
276260
const slowNavigation = startSlowNavigation(slowId)
277261

278262
await waitForSlowLoader(slowId)
279-
const slowLoadPromise = getLatestLoadPromise()
280-
281-
if (!slowLoadPromise) {
282-
throw new Error(`Slow navigation did not start a load for id: ${slowId}`)
283-
}
284-
285263
await navigateFast(fastId)
286264
resolveSlowLoader(slowId)
287265

@@ -291,7 +269,6 @@ export function createWorkload(
291269
assertSlowNavigationSettlement(settlement)
292270
}
293271

294-
await awaitExpectedLoadSettlement(slowLoadPromise)
295272
await drainMicrotasks()
296273
}
297274

‎benchmarks/memory/server/scenarios/aborted-requests/shared.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@ const textDecoder = new TextDecoder()
2727
const abortedRequestModes: Record<Framework, AbortedRequestMode> = {
2828
react: {
2929
readMode: 'first-chunk',
30-
cancelMode: 'plain',
30+
cancelMode: 'swallow-abort-error',
3131
},
3232
solid: {
3333
readMode: 'first-chunk',
34-
cancelMode: 'plain',
34+
cancelMode: 'swallow-abort-error',
3535
},
3636
vue: {
3737
readMode: 'shell-before-deferred',

‎docs/router/api/router/RouteMatchType.md‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,26 @@ interface RouteMatch {
1111
routeId: string
1212
pathname: string
1313
params: Route['allParams']
14-
status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound'
14+
status: 'pending' | 'success' | 'error' | 'notFound'
1515
isFetching: false | 'beforeLoad' | 'loader'
16-
showPending: boolean
1716
error: unknown
1817
paramsError: unknown
1918
searchError: unknown
2019
updatedAt: number
2120
loaderData?: Route['loaderData']
2221
context: Route['allContext']
2322
search: Route['fullSearchSchema']
24-
fetchedAt: number
2523
abortController: AbortController
26-
cause: 'enter' | 'stay'
24+
cause: 'preload' | 'enter' | 'stay'
2725
ssr?: boolean | 'data-only'
2826
}
2927
```
28+
29+
`status` describes the match's render state. `isFetching` independently exposes
30+
active `beforeLoad` or loader work. In particular, a successful match can report
31+
`isFetching: 'loader'` while stale data remains visible during a background
32+
reload.
33+
34+
The router state can contain matches below the pending, error, or not-found
35+
boundary. Those matches remain observable as part of the structurally matched
36+
lane even though the route renderer stops at the boundary.

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

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ The `RouteOptions` type accepts an object with the following properties:
5656
- Type: `(rawSearchParams: unknown) => TSearchSchema`
5757
- Optional
5858
- A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search 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 does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router.
59+
- This is a planning callback. It must be deterministic and side-effect-free for the same input; do not navigate or mutate application/router state from it.
5960
- Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `<Link />` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters.
6061

6162
### `search.middlewares` property
@@ -70,6 +71,7 @@ The `RouteOptions` type accepts an object with the following properties:
7071
- Type: `(rawParams: Record<string, string>) => TParams`
7172
- Optional
7273
- 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 does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
74+
- This is a planning callback. It must be deterministic and side-effect-free for the same input.
7375

7476
### `stringifyParams` method (⚠️ deprecated, use `params.stringify` instead)
7577

@@ -82,6 +84,7 @@ The `RouteOptions` type accepts an object with the following properties:
8284
- Type: `(rawParams: Record<string, string>) => TParams | false`
8385
- Optional
8486
- 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.
87+
- This is a planning callback. It must be deterministic and side-effect-free for the same input.
8588
- Experimental: returning `false` during incoming route matching skips this route and allows matching to continue to another candidate route.
8689

8790
### `params.priority` property
@@ -176,6 +179,7 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
176179
177180
- Optional
178181
- A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation.
182+
- This is a planning callback and cache-key function. It must be deterministic and side-effect-free for the same validated search input. The returned value and any serialization methods on it, such as `toJSON`, must also be side-effect-free.
179183
- By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here.
180184
- If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the `loader`'s `deps` argument.
181185
@@ -191,14 +195,14 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
191195
- Type: `number`
192196
- Optional
193197
- Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds)
194-
- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal `staleTime` is used instead.
198+
- The amount of time in milliseconds that loader data produced by a preload is considered fresh. Another preload or the first navigation can reuse it within this interval. After navigation accepts the generation, subsequent freshness uses `staleTime`.
195199
196200
### `gcTime` property
197201
198202
- Type: `number`
199203
- Optional
200-
- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes.
201-
- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use.
204+
- Defaults to `routerOptions.defaultGcTime`, which defaults to 5 minutes.
205+
- The amount of time in milliseconds that loader data from an ordinary load will be kept in memory after it is no longer in use.
202206
203207
### `shouldReload` property
204208
@@ -234,12 +238,12 @@ type loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
234238
- Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500`
235239
- The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second.
236240
237-
### `preloadMaxAge` property
241+
### `preloadGcTime` property
238242
239243
- Type: `number`
240244
- Optional
241-
- Defaults to `30_000` ms (30 seconds)
242-
- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded.
245+
- Defaults to `routerOptions.defaultPreloadGcTime`, which defaults to 5 minutes.
246+
- The amount of time in milliseconds that loader data produced by a preload can remain in memory while it is not in use. This controls retention; use `preloadStaleTime` to control whether retained data is fresh enough to reuse without reloading.
243247
244248
### `preSearchFilters` property (⚠️ deprecated, use `search.middlewares` instead)
245249

‎docs/router/api/router/RouterOptionsType.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -129,14 +129,14 @@ The `RouterOptions` type accepts an object with the following properties and met
129129

130130
- Type: `number`
131131
- Optional
132-
- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes.
132+
- Defaults to 5 minutes.
133133
- The default `preloadGcTime` a route should use if no preloadGcTime is provided.
134134

135135
### `defaultGcTime` property
136136

137137
- Type: `number`
138138
- Optional
139-
- Defaults to 30 minutes.
139+
- Defaults to 5 minutes.
140140
- The default `gcTime` a route should use if no gcTime is provided.
141141

142142
### `defaultOnCatch` property

‎docs/router/api/router/RouterStateType.md‎

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,17 @@ id: RouterStateType
33
title: RouterState type
44
---
55

6-
The `RouterState` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc.
6+
The `RouterState` type represents the observable state of the router, including
7+
the requested and resolved locations, match presentation, and foreground loading
8+
status.
79

810
```tsx
911
type RouterState = {
1012
status: 'pending' | 'idle'
1113
isLoading: boolean
12-
isTransitioning: boolean
1314
matches: Array<RouteMatch>
1415
location: ParsedLocation
15-
resolvedLocation: ParsedLocation
16+
resolvedLocation?: ParsedLocation
1617
}
1718
```
1819
@@ -23,22 +24,24 @@ The `RouterState` type contains all of the properties that are available on the
2324
### `status` property
2425
2526
- Type: `'pending' | 'idle'`
26-
- The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route.
27+
- The current foreground status of the router. `pending` means the requested route is still loading or waiting for its framework transition to settle.
2728
2829
### `isLoading` property
2930
3031
- Type: `boolean`
31-
- `true` if the router is currently loading a route or waiting for a route to finish loading.
32-
33-
### `isTransitioning` property
34-
35-
- Type: `boolean`
36-
- `true` if the router is currently transitioning to a new route.
32+
- `true` when `status` is `pending`.
33+
- Background loader refreshes do not change this value. Inspect each match's `isFetching` field to observe foreground `beforeLoad`/loader work and background loader work.
3734
3835
### `matches` property
3936
4037
- Type: [`Array<RouteMatch>`](./RouteMatchType.md)
41-
- An array of all of the route matches that have been resolved and are currently active.
38+
- The match presentation currently exposed to the application.
39+
- A navigation can keep the previous presentation visible until pending UI is
40+
published. Once the destination is presented, this contains its complete
41+
structurally matched lane, including descendants that are still loading.
42+
- Error and not-found results also preserve the complete structurally matched
43+
lane. Rendering stops at the selected pending or terminal boundary; it does
44+
not truncate this array.
4245
4346
### `location` property
4447
@@ -47,5 +50,5 @@ The `RouterState` type contains all of the properties that are available on the
4750
4851
### `resolvedLocation` property
4952
50-
- Type: [`ParsedLocation`](./ParsedLocationType.md)
51-
- The location that the router has resolved and loaded.
53+
- Type: [`ParsedLocation`](./ParsedLocationType.md) | `undefined`
54+
- The location whose load and framework transition have settled. It is `undefined` before the initial location resolves.

0 commit comments

Comments
 (0)