fix: commit route context #6053
main fromrefs/pull/6053/head·merged by schiller-manuel(GitHub profile, opens in a new tab) fixes #6040
Summary by CodeRabbit#
Bug Fixes
- Ensured route context is consistently merged and committed only after loaders complete, preventing components from seeing incomplete context during immediate navigations.
Tests
- Added tests that validate route context during immediate navigation after beforeLoad-like operations.
- Relaxed and adjusted numerous navigation update-count assertions to stable ranges or updated expectations to reduce flakiness.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: react-router
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router
View your CI Pipeline Execution ↗ for commit 562ad189a66105b8801ce062dfc563c8a23f810a
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 8m View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1m 36s View ↗
☁️ Nx Cloud last updated this comment at
2025-12-09 20:03:07UTCMore templates
- tanstack-router-vue-example-basic-jsx
- tanstack-router-vue-example-basic-file-based-jsx
- tanstack-router-vue-example-basic-file-based-sfc
- tanstack-router-react-example-authenticated-routes
- tanstack-router-react-example-authenticated-routes-firebase
- tanstack-router-react-example-basic
- tanstack-router-react-example-basic-default-search-params
- tanstack-router-react-example-basic-devtools-panel
- tanstack-router-react-example-basic-file-based
- tanstack-router-react-example-basic-non-nested-devtools
- tanstack-router-react-example-react-query
- tanstack-router-react-example-basic-react-query-file-based
- tanstack-router-react-example-basic-ssr-file-based
- tanstack-router-react-example-basic-ssr-streaming-file-based
- tanstack-router-react-example-basic-virtual-file-based
- tanstack-router-react-example-basic-virtual-inside-file-based
- tanstack-router-react-example-deferred-data
- tanstack-router-i18n-paraglide
- tanstack-router-react-example-kitchen-sink
- tanstack-router-react-example-kitchen-sink-file-based
- tanstack-router-react-example-kitchen-sink-react-query
- tanstack-router-react-example-kitchen-sink-react-query-file-based
- tanstack-router-react-example-large-file-based
- tanstack-router-react-example-location-masking
- tanstack-router-react-example-navigation-blocking
- tanstack-router-react-example-quickstart
- tanstack-router-react-example-quickstart-esbuild-file-based
- tanstack-router-react-example-quickstart-file-based
- tanstack-router-react-example-quickstart-rspack-file-based
- tanstack-router-react-example-quickstart-webpack-file-based
- router-monorepo-react-query
- router-mono-simple
- router-mono-simple-lazy
- tanstack-router-react-example-scroll-restoration
- tanstack-search-validator-adapters
- tanstack-start-example-bare
- tanstack-start-example-basic
- tanstack-start-example-basic-auth
- tanstack-router-react-example-basic-authjs
- tanstack-start-example-basic-cloudflare
- tanstack-start-example-basic-react-query
- tanstack-start-example-basic-rsc
- tanstack-start-example-basic-static
- tanstack-start-bun-hosting
- tanstack-start-example-clerk-basic
- tanstack-start-example-convex-trellaux
- tanstack-start-example-counter
- tanstack-start-i18n-paraglide
- tanstack-start-example-large
- tanstack-start-example-material-ui
- tanstack-start-streaming-data-from-server-functions
- tanstack-start-example-supabase-basic
- tanstack-start-tailwind-v4
- tanstack-start-example-trellaux
- tanstack-start-example-workos
- tanstack-router-react-example-view-transitions
- tanstack-router-react-example-with-framer-motion
- tanstack-router-react-example-with-trpc
- tanstack-router-react-example-with-trpc-react-query
- tanstack-router-solid-example-authenticated-routes
- tanstack-router-solid-example-authenticated-routes-firebase
- tanstack-router-solid-example-basic
- tanstack-router-solid-example-basic-default-search-params
- tanstack-router-solid-example-basic-devtools-panel
- tanstack-router-solid-example-basic-file-based
- tanstack-router-solid-example-basic-non-nested-devtools
- tanstack-router-solid-example-basic-solid-query
- tanstack-router-solid-example-basic-solid-query-file-based
- tanstack-router-solid-example-basic-ssr-file-based
- tanstack-router-solid-example-basic-ssr-streaming-file-based
- tanstack-router-solid-example-basic-virtual-file-based
- tanstack-router-solid-example-basic-virtual-inside-file-based
- tanstack-router-solid-example-deferred-data
- tanstack-router-solid-i18n-paraglide
- tanstack-router-solid-example-kitchen-sink
- tanstack-router-solid-example-kitchen-sink-file-based
- tanstack-router-solid-example-kitchen-sink-solid-query
- tanstack-router-solid-example-kitchen-sink-solid-query-file-based
- tanstack-router-solid-example-large-file-based
- tanstack-router-solid-example-location-masking
- tanstack-router-solid-example-navigation-blocking
- tanstack-router-solid-example-quickstart
- tanstack-router-solid-example-quickstart-esbuild-file-based
- tanstack-router-solid-example-quickstart-file-based
- tanstack-router-solid-example-quickstart-rspack-file-based
- tanstack-router-solid-example-quickstart-webpack-file-based
- @tanstack/router-solid-mono-simple
- router-solid-mono-simple-lazy
- router-solid-monorepo-solid-query
- tanstack-router-solid-example-scroll-restoration
- tanstack-solid-router-search-validator-adapters
- tanstack-solid-start-example-basic
- tanstack-solid-start-example-basic-auth
- tanstack-solid-start-example-basic-authjs
- tanstack-solid-start-example-basic-cloudflare
- tanstack-solid-start-example-basic-netlify
- tanstack-solid-start-example-basic-nitro
- tanstack-start-example-basic-solid-query
- tanstack-solid-start-example-basic-static
- tanstack-solid-start-bun-hosting
- tanstack-solid-start-example-convex-better-auth
- tanstack-solid-start-example-counter
- tanstack-solid-start-i18n-paraglide
- tanstack-solid-start-example-large
- tanstack-solid-start-streaming-data-from-server-functions
- tanstack-solid-start-example-supabase-basic
- tanstack-solid-start-tailwind-v4
- tanstack-router-solid-example-view-transitions
- tanstack-router-solid-example-with-framer-motion
- tanstack-router-solid-example-with-trpc
@tanstack/arktype-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@6053@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@6053@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@6053@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@6053@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@6053@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@6053@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@6053@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@6053@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@6053@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@6053@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@6053@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@6053@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@6053@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@6053@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@6053@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@6053@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@6053@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@6053@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@6053@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@6053@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@6053@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@6053@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@6053@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@6053@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@6053@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@6053@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@6053@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@6053@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@6053@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@6053@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@6053@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@6053@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@6053@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@6053@tanstack/vue-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router@6053@tanstack/vue-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router-devtools@6053@tanstack/vue-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router-ssr-query@6053@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@6053commit:
562ad18Actionable comments posted: 1
🧹 Nitpick comments (3)
packages/react-router/tests/store-updates-during-navigation.test.tsx (1)
139-139: Document rationale for higher update counts and consider relaxing overly brittle assertionsThe new expectations reflect extra store updates after the route-context commit changes, but the tests still read as "these numbers should not increase" without explaining why some increases are acceptable (e.g. now 12/10/19 updates). For future maintainers, it would help to briefly note that the additional updates are due to the new context commit path rather than accidental regressions, and, where behavior is known to vary (like the “nothing” case), prefer bounded ranges over exact counts to avoid unnecessary flakiness or churn when internal batching changes again.
Also applies to: 157-157, 173-173, 184-185, 226-226, 242-242, 258-258, 274-274, 292-292
packages/solid-router/tests/routeContext.test.tsx (1)
5-5: Solid immediate‑navigation context test looks good; tighten assertion and update stale noteThe new Solid test correctly exercises the “sleep in beforeLoad + immediate navigation” scenario and the
createEffect‑based tracking ofuseRouteContext()is a good fit. Two small follow‑ups:- The note above the test now claims it passes only in solid-router but fails in react-router, which is no longer accurate given the new React test; consider updating or removing that comment to avoid confusion.
- To guard against a vacuous pass if
contextValueswere ever empty, add an assertion likeexpect(contextValues.length).toBeGreaterThan(0)before theevery(...)check.
Also applies to: 2396-2452
packages/react-router/tests/routeContext.test.tsx (1)
12-12: React immediate‑navigation context test is solid; consider a non‑empty guard oncontextValuesThe new React test accurately mirrors the Solid scenario and validates that
useRouteContext()never exposes a pre‑beforeLoad context during immediate navigation; theuseEffect+navigatepattern is appropriate here, even underreactStrictModewhere the effect may fire twice.To make the assertion more robust, you might also assert that
contextValues.length > 0before calling.every(...), so the test can’t pass if, for some reason, the root component stopped rendering oruseRouteContext()stopped producing values.Also applies to: 2479-2532
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 98dc05073dcf7490d38f9158833f3df22c005e96 and 42d4a67a6ef1c41e4bfeee5a79bf8264555fa925.
📒 Files selected for processing (4)
packages/react-router/tests/routeContext.test.tsx(2 hunks)packages/react-router/tests/store-updates-during-navigation.test.tsx(9 hunks)packages/router-core/src/load-matches.ts(7 hunks)packages/solid-router/tests/routeContext.test.tsx(2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript strict mode with extensive type safety for all code
Files:
packages/react-router/tests/routeContext.test.tsxpackages/react-router/tests/store-updates-during-navigation.test.tsxpackages/solid-router/tests/routeContext.test.tsxpackages/router-core/src/load-matches.ts
**/*.{js,ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Implement ESLint rules for router best practices using the ESLint plugin router
Files:
packages/react-router/tests/routeContext.test.tsxpackages/react-router/tests/store-updates-during-navigation.test.tsxpackages/solid-router/tests/routeContext.test.tsxpackages/router-core/src/load-matches.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/react-router/tests/routeContext.test.tsxpackages/react-router/tests/store-updates-during-navigation.test.tsxpackages/solid-router/tests/routeContext.test.tsxpackages/router-core/src/load-matches.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
🔇 Additional comments (1)
packages/router-core/src/load-matches.ts (1)
381-387: Before‑load context refactor and loader context aggregation look consistent with the new semanticsThe changes in
executeBeforeLoadandgetLoaderContextare a clear improvement:pending()andupdateContext()no longer mutatematch.contextmid‑beforeLoad; they only flip fetching flags and stash results into__beforeLoadContext, which avoids exposing partially‑merged context to components.- The beforeLoad
contextargument now merges router context, parentcontext, parent__beforeLoadContext, and the current route’s__routeContext, so child beforeLoads always see parent contributions even when the parent’s context hasn’t been committed yet. - Loader context is now derived by walking
inner.matches[0..index]and merging each match’s__routeContextand__beforeLoadContext, which produces a deterministic aggregate regardless of load ordering and matches how tests expect composed context to behave.
This structure matches the intent of the new route‑context tests in both React and Solid and keeps the “source of truth” for composition in the non‑reactive fields rather than
match.contextitself.Also applies to: 398-400, 426-432, 459-465, 572-584
packages/router-core/src/load-matches.ts lines 749 to 766OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -742,3 +746,21 @@742746 let loaderIsRunningAsync = false743747 const route = inner.router.looseRoutesById[routeId]!744748749+ // Helper to compute and commit context after loader completes750+ const commitContext = () => {751+ const parentMatchId = inner.matches[index - 1]?.id752+ const parentMatch = parentMatchId753+ ? inner.router.getMatch(parentMatchId)!754+ : undefined755+ const parentContext =756+ parentMatch?.context ?? inner.router.options.context ?? undefined757+758+ inner.updateMatch(matchId, (prev) => ({759+ ...prev,760+ context: {761+ ...parentContext,762+ ...prev.__routeContext,763+ ...prev.__beforeLoadContext,764+ },765+ }))766+ }🛠️ Refactor suggestion | 🟠 Major
commitContextdepends on parent commit ordering; recommend mirroring the loader aggregation to avoid racey child contextsRight now
commitContextbuilds a match’scontextfrom:const parentMatch = /* previous match */ const parentContext = parentMatch?.context ?? inner.router.options.context ?? undefined inner.updateMatch(matchId, (prev) => ({ ...prev, context: { ...parentContext, ...prev.__routeContext, ...prev.__beforeLoadContext, }, }))and it’s invoked:
- In the async loader path, after
runLoadercompletes. - At the end of
loadRouteMatchwhenloaderIsRunningAsyncis false.
Because loaders for all matches are kicked off in parallel and awaited via
Promise.all, a child route’scommitContextcan execute before its parent’s when the parent’s loader (or head/scripts/pending) takes longer. In that case,parentMatch.contextstill holds its pre‑commit value, so the child’s committedcontextwill not include the parent’s__routeContext/__beforeLoadContextcontributions—even though loader/beforeLoad contexts themselves already see the fully aggregated data viagetLoaderContext.To make
contextcomposition independent of loader timing, consider changingcommitContextto mirror the aggregation logic ingetLoaderContext, e.g.:- const commitContext = () => { - const parentMatchId = inner.matches[index - 1]?.id - const parentMatch = parentMatchId - ? inner.router.getMatch(parentMatchId)! - : undefined - const parentContext = - parentMatch?.context ?? inner.router.options.context ?? undefined - - inner.updateMatch(matchId, (prev) => ({ - ...prev, - context: { - ...parentContext, - ...prev.__routeContext, - ...prev.__beforeLoadContext, - }, - })) - } + const commitContext = () => { + let context = inner.router.options.context ?? {} + + for (let i = 0; i <= index; i++) { + const innerMatch = inner.matches[i] + if (!innerMatch) continue + const m = inner.router.getMatch(innerMatch.id) + if (!m) continue + + context = { + ...context, + ...(m.__routeContext ?? {}), + ...(m.__beforeLoadContext ?? {}), + } + } + + inner.updateMatch(matchId, (prev) => ({ + ...prev, + context, + })) + }This way, each match’s
contextis always derived from the same aggregated inputs as loader/beforeLoad, regardless of whether the parent’s loader is faster or slower.Optionally, you may also want to call
commitContext()in theinner.router.isServer && shouldSkipLoader(...)early‑return branch so that server‑side matches withssr: falsestill end up with a consistentcontextvalue if anything relies on it.Also applies to: 842-843, 881-885
✅ Addressed in commits 131445c to 562ad18
Is this a valid concern?
@tannerlinsley Yes, this is a valid concern. Let me break down the race condition:
The Problem#
Loaders run in parallel - After all
beforeLoadcalls complete serially, the code kicks off all loaders in parallel:for (let i = 0; i < max; i++) { inner.matchPromises.push(loadRouteMatch(inner, i)) } await Promise.all(inner.matchPromises)Child can finish before parent - If a parent route has a slow loader (e.g., fetching data) and a child route has a fast/no loader, the child's
commitContext()will execute first.commitContext reads parent's
.context- When the child commits, it reads:const parentContext = parentMatch?.context ?? ...At this point, the parent hasn't called its own
commitContext()yet, soparentMatch.contextis stale (doesn't include parent's__beforeLoadContext).Inconsistency - During loader execution,
getLoaderContextcorrectly aggregates all parent contexts (lines 680-693), but the final committedcontextthat components see can be incomplete.
The Fix#
The suggested fix mirrors the aggregation logic from
getLoaderContext, makingcommitContextcompute from__routeContext/__beforeLoadContextdirectly rather than relying on parent's committed.context. This eliminates the timing dependency.Recommendation#
I'd implement the suggested fix to ensure
match.contextis always consistent regardless of loader completion order. This is especially important since components usematch.contextdirectly viauseRouteContext().i adapted your idea but used a slightly more performant implementation. please review the latest changes @coderabbitai
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash # Fetch the latest version of the file from the PR branch git fetch origin pull/6053/head:pr-6053 git checkout pr-6053 cat packages/router-core/src/load-matches.ts | grep -A 30 "const commitContext = ()"Length of output: 985
@schiller-manuel Excellent! Your implementation looks great. 👍
What you changed:
- Used
Object.assign(context, m.__routeContext, m.__beforeLoadContext)instead of spreading - Changed from
lettoconstsince you're mutating in-place - Removed the
?? {}null coalescing (unnecessary sinceObject.assignignoresundefined)
Why it's better:
- ✅ More performant - Mutates in-place instead of creating a new object on each iteration
- ✅ Still fixes the race condition - Aggregates from
__routeContext/__beforeLoadContextdirectly, not from parent's committed.context - ✅ Cleaner code - Fewer unnecessary operations
The core fix is intact: each match's
contextis now computed from the raw__routeContext/__beforeLoadContextvalues of all ancestors, making it independent of loader completion order. Your optimization simply makes that aggregation more efficient.Great work! 🎉
🐰✨
(\(\ (˶ᵔ ᵕ ᵔ˶) /づ🔧💡
🧬 Code Graph Analysis Results
- File: packages/router-core/src/utils.ts, lines 471-479
export function isPromise<T>( value: Promise<Awaited<T>> | T, ): value is Promise<Awaited<T>> { return Boolean( value && typeof value === 'object' && typeof (value as Promise<T>).then === 'function', ) }- File: packages/router-core/src/router.ts, lines 736-739
export type UpdateMatchFn = ( id: string, updater: (match: AnyRouteMatch) => AnyRouteMatch, ) => void- File: packages/router-core/src/Matches.ts, lines 220-240
export type MakeRouteMatch< TRouteTree extends AnyRoute = RegisteredRouter['routeTree'], TRouteId = RouteIds<TRouteTree>, TStrict extends boolean = true, > = RouteMatch< TRouteId, RouteById<TRouteTree, TRouteId>['types']['fullPath'], TStrict extends false ? AllParams<TRouteTree> : RouteById<TRouteTree, TRouteId>['types']['allParams'], TStrict extends false ? FullSearchSchema<TRouteTree> : RouteById<TRouteTree, TRouteId>['types']['fullSearchSchema'], TStrict extends false ? AllLoaderData<TRouteTree> : RouteById<TRouteTree, TRouteId>['types']['loaderData'], TStrict extends false ? AllContext<TRouteTree> : RouteById<TRouteTree, TRouteId>['types']['allContext'], RouteById<TRouteTree, TRouteId>['types']['loaderDeps'] >- File: packages/router-core/src/Matches.ts, line 242
export type AnyRouteMatch = RouteMatch<any, any, any, any, any, any, any>- File: packages/router-core/src/index.ts, lines 208-208
AnyRouter- File: packages/router-core/src/index.ts, lines 72-72
ParsedLocation- File: packages/router-core/src/route.ts, lines 1085-1104
export interface SsrContextOptions< in out TParentRoute extends AnyRoute, in out TSearchValidator, in out TParams, > { params: | { status: 'success' value: Expand<ResolveAllParamsFromParent<TParentRoute, TParams>> } | { status: 'error'; error: unknown } search: | { status: 'success' value: Expand<ResolveFullSearchSchema<TParentRoute, TSearchValidator>> } | { status: 'error'; error: unknown } location: ParsedLocation matches: Array<MakePreValidationErrorHandlingRouteMatchUnion> }github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: vue-router
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/solid-router/tests/store-updates-during-navigation.test.tsx (1)
125-298: Align flakiness comments and expectations, and consider ranges everywhereThe relaxed assertions using
toBeGreaterThanOrEqual/toBeLessThanOrEqualfor the async cases are a good way to handle small variability.Two minor points:
- The comments still say “sometimes (rarely) is 12” / “7”, but the upper bounds are now
<= 13/<= 8. It’d be clearer to either generalize the comment (“occasionally higher”) or update the numbers to match. - For the other tests that now use exact counts (7, 10, 19, 9, 7, 3), you might want to consider
<= Nstyle expectations as in the flaky ones, so the suite continues to guard against too many updates without overfitting to exact internals.
packages/react-router/tests/store-updates-during-navigation.test.tsx (1)
125-294: Keep flaky‑test comments in sync with bounds and avoid over‑fitting exact countsThe move to
[11,13]and[8,9]ranges is a sensible way to account for minor variability in update counts.Two small follow‑ups:
- The comments still say “sometimes (rarely) is 12”, but
updatesis now allowed up to 13; it’d be good to either relax the wording or adjust the numbers so future readers aren’t surprised. - For the remaining tests with exact
toBe(...)expectations, you might consider<= Nor a tight range (as in the first and “nothing” tests), which better matches the suite’s intent (“doesn't update too many times”) and reduces churn when internal scheduling changes but behavior is still acceptable.
packages/router-core/src/load-matches.ts (1)
367-373: BeforeLoad context may miss ancestorbeforeLoadvalues for the current navigationbeforeLoadFnContext.contextaggregates as:const parentMatchContext = parentMatch?.context ?? inner.router.options.context ?? undefined context: { ...parentMatchContext, ...parentMatch?.__beforeLoadContext, ...match.__routeContext, }However, the execution model runs all
beforeLoadhooks sequentially first (lines 921–927), then all loaders in parallel (lines 929–931). This means when a deep child'sbeforeLoadexecutes:parentMatch.contextstill reflects the previous navigation (sincecommitContext()is only called after loaders complete, at line 840 or 882)- you only include the immediate parent's
__beforeLoadContext, not any grandparent or deeper ancestor values from the current navigation
In contrast, loaders (via
getLoaderContext, lines 562–606) and the finalmatch.context(viacommitContext, lines 749–764) both aggregate all ancestors'__routeContextand__beforeLoadContextby looping0..index, ensuring consistent context across a deep match hierarchy.If the design intent is for each
beforeLoadto see the same aggregated context available to loaders and components for the same ancestors, mirror the aggregation strategy ingetLoaderContext—walkinner.matches[0..index-1]and fold their__routeContextand__beforeLoadContextrather than relying on the potentially staleparentMatch.context.🧹 Nitpick comments (2)
packages/vue-router/tests/store-updates-during-navigation.test.tsx (1)
126-305: Consider preferring upper bounds/ranges over exact update counts for long‑term stabilityThe updated expectations (33, 13, 31, 23, 47, 24, 22, 18, 7) look consistent with the new context/loader behavior, but asserting exact counts for most cases makes these tests quite brittle to internal refactors.
Since this suite is already framed as “doesn't update too many times” and you’re already using
>=/<=bounds for the “nothing” case, it may be more robust to standardize on “≤ N” (or a small range) instead of stricttoBe(N)here as well, so small internal re-orderings don’t force mechanical test updates while still catching real regressions.packages/router-core/src/load-matches.ts (1)
444-467: Nice fix on context commit ordering; consider centralizing aggregation helper and tightening base context handlingThe new strategy:
- storing only
__beforeLoadContextinexecuteBeforeLoad, - computing loader
contextingetLoaderContextby folding__routeContext+__beforeLoadContextfor matches up toindex, and - committing
match.contextincommitContext()after loaders complete (or are skipped),
correctly removes the old dependence on parent commit timing and makes
contextdeterministic with respect to the match tree rather than loader ordering. This directly addresses the prior race onmatch.context.Two small follow‑ups you might consider:
DRY aggregation logic
getLoaderContextandcommitContextare nearly identical in how they aggregate:let context = inner.router.options.context ?? {} for (let i = 0; i <= index; i++) { const m = inner.router.getMatch(inner.matches[i]!.id) context = { ...context, ...(m.__routeContext ?? {}), ...(m.__beforeLoadContext ?? {}), } }versus:
const context = { ...inner.router.options.context } for (let i = 0; i <= index; i++) { const m = inner.router.getMatch(innerMatch.id) Object.assign(context, m.__routeContext, m.__beforeLoadContext) }Extracting a shared helper (e.g.
buildContextUntilIndex(inner, index)) would keep loader and committed contexts in lockstep and reduce the chance of subtle divergence later.Defensive base context initialization
getLoaderContextusesinner.router.options.context ?? {}, which safely handlesundefined/null.commitContextuses object spread oninner.router.options.context, which will throw if someone ever passesnull.Matching
getLoaderContext’s pattern here (e.g. start fromconst base = inner.router.options.context ?? {}; const context = { ...base };) would guard against that edge case and keep both call sites consistent.
Also applies to: 562-584, 749-764, 879-883
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 42d4a67a6ef1c41e4bfeee5a79bf8264555fa925 and 562ad189a66105b8801ce062dfc563c8a23f810a.
📒 Files selected for processing (4)
packages/react-router/tests/store-updates-during-navigation.test.tsx(9 hunks)packages/router-core/src/load-matches.ts(7 hunks)packages/solid-router/tests/store-updates-during-navigation.test.tsx(8 hunks)packages/vue-router/tests/store-updates-during-navigation.test.tsx(9 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use TypeScript strict mode with extensive type safety for all code
Files:
packages/solid-router/tests/store-updates-during-navigation.test.tsxpackages/react-router/tests/store-updates-during-navigation.test.tsxpackages/vue-router/tests/store-updates-during-navigation.test.tsxpackages/router-core/src/load-matches.ts
**/*.{js,ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Implement ESLint rules for router best practices using the ESLint plugin router
Files:
packages/solid-router/tests/store-updates-during-navigation.test.tsxpackages/react-router/tests/store-updates-during-navigation.test.tsxpackages/vue-router/tests/store-updates-during-navigation.test.tsxpackages/router-core/src/load-matches.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad Repo: TanStack/router PR: 5402 File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21 Timestamp: 2025-10-08T08:11:47.088Z Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.Applied to files:
packages/solid-router/tests/store-updates-during-navigation.test.tsxpackages/react-router/tests/store-updates-during-navigation.test.tsxpackages/vue-router/tests/store-updates-during-navigation.test.tsx
📚 Learning: 2025-12-06T15:03:07.223Z
Learnt from: CR Repo: TanStack/router PR: 0 File: AGENTS.md:0-0 Timestamp: 2025-12-06T15:03:07.223Z Learning: Add or update tests for any code changesApplied to files:
packages/solid-router/tests/store-updates-during-navigation.test.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Preview
- GitHub Check: Test
- The comments still say “sometimes (rarely) is 12” / “7”, but the upper bounds are now
Sign in to join this conversation.
Walkthrough#
Deferred route-context merging: router-core no longer mutates the shared context during beforeLoad execution but records per-match beforeLoad context and commits a merged context after loaders complete. Tests for React and Solid validate context during immediate navigation; several store-update test expectations were relaxed/increased.
Changes#
packages/router-core/src/load-matches.ts__beforeLoadContext,commitContextto compute/persist merged context after loader completion; updated getLoaderContext and beforeLoadFnContext to aggregate contexts without mid-beforeLoad exposure.packages/react-router/tests/routeContext.test.tsxuseEffectimport.packages/solid-router/tests/routeContext.test.tsxcreateEffect/onMountthat delay in root.beforeLoad, navigate immediately from index route, record captured route context values, and assert consistency.packages/react-router/tests/store-updates-during-navigation.test.tsx,packages/solid-router/tests/store-updates-during-navigation.test.tsx,packages/vue-router/tests/store-updates-during-navigation.test.tsxSequence Diagram(s)#
mermaid sequenceDiagram autonumber participant App as App / Component participant Router as Router Core participant Match as Route Match participant beforeLoad as beforeLoad fn participant Loader as Loader (async) Note over App,Router: Navigation starts (e.g., index route mounts and navigates) App->>Router: navigate(path) Router->>Match: loadRouteMatch(index) Match->>beforeLoad: executeBeforeLoad(context snapshot) beforeLoad-->>Match: returns __beforeLoadContext (async) Note over Match,Loader: beforeLoad resolves but context not merged yet Router->>Loader: run loader(s) (may be async) Loader-->>Router: loader results Router->>Router: commitContext() -- merge parent.__routeContext + __beforeLoadContext + route.__routeContext Router->>App: render with committed merged context App->>Match: useRouteContext() reads committed context
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
packages/router-core/src/load-matches.ts— verify async/sync paths both commit context correctly and do not expose partial context during beforeLoad.Possibly related PRs#
Suggested reviewers#
Poem#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.