Fix: Route with server function as loader that throws notFound crashes route on HMR #5763 #5890
main fromrefs/pull/5890/head·merged by birkskyum(GitHub profile, opens in a new tab) Resolves: #5763
- Updated packages/router-core/src/router.ts to treat 'notFound' like 'error' in invalidate
- Added a new test in packages/react-router/tests/router.test.tsx that verifies a route returning a 404 notFound
Summary by CodeRabbit#
New Features
- Added a public invalidate API to mark routes (optionally via a filter) for reset so their loaders re-run.
Bug Fixes
- Routes stuck in "not found" or error states now reset to pending when invalidated, ensuring loaders re-run and the correct content or not-found UI is shown.
Tests
- Added regression tests covering filtered (HMR-style) and global invalidation to verify loaders re-run and not-found UI remains shown as expected.
- 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
View your CI Pipeline Execution ↗ for commit 32a3f09d127015ba8cee6353eb83d24fabf40afc
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 9m 53s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1m 25s View ↗
☁️ Nx Cloud last updated this comment at
2025-11-19 16:08:19UTCActionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 3cd2f158275f991c1874e2b33a036d5fef122d3a and 68e25a90e0c21d201710cd10cec50cb503fd0cee.
📒 Files selected for processing (2)
packages/react-router/tests/router.test.tsx(1 hunks)packages/router-core/src/router.ts(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/react-router/tests/router.test.tsx
🧰 Additional context used
🧠 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-01T18:30:26.591Z
Learnt from: schiller-manuel Repo: TanStack/router PR: 5330 File: packages/router-core/src/router.ts:2231-2245 Timestamp: 2025-10-01T18:30:26.591Z Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.Applied to files:
packages/router-core/src/router.ts
📚 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/router-core/src/router.ts
@@ -2318,4 +2318,6 @@23182318 return {23192319 ...d,23202320 invalid: true,2321- ...(opts?.forcePending || d.status === 'error'2321+ ...(opts?.forcePending ||2322+ d.status === 'error' ||2323+ d.status === 'notFound'⚠️ Potential issue | 🟡 Minor
🧩 Analysis chain
LGTM! The fix correctly treats
notFoundstatus likeerrorduring invalidation.The change ensures that matches with
status === 'notFound'are reset to'pending'when invalidated, allowing them to be reloaded. This is essential for HMR scenarios where route definitions may have changed, and prevents the crash described in issue #5763.To ensure consistency, verify whether other status checks in the codebase should also treat
'error'and'notFound'similarly:
🏁 Script executed:
#!/bin/bash # Description: Find other locations where 'error' status is checked to determine if 'notFound' should also be included # Search for status === 'error' checks rg -n "status === ['\"]error['\"]" --type=ts -C 3 # Search for status !== 'error' checks rg -n "status !== ['\"]error['\"]" --type=ts -C 3 # Search for d.status checks to see the pattern rg -n "\.status === ['\"]" --type=ts -C 2Length of output: 78370
--- 🏁 Script executed: ```shell #!/bin/bash # Get context around line 2135 to understand exitingMatches and cachedMatches usage # Also check how exitingMatches is populated and what the intent is echo "=== Context around exitingMatches filtering at line 2135 ===" sed -n '2120,2150p' packages/router-core/src/router.ts echo "" echo "=== Search for where exitingMatches is defined/used ===" rg -n "exitingMatches" packages/router-core/src/router.ts -B 5 -A 5 echo "" echo "=== Check if there's a corresponding filter for notFound elsewhere ===" rg -n "status !== ['\"]notFound['\"]" packages/router-core/src/router.ts -C 2Length of output: 3408
🏁 Script executed:
#!/bin/bash # Understand cachedMatches usage and lifecycle hooks echo "=== How is cachedMatches used? Search for cachedMatches access ===" rg -n "cachedMatches" packages/router-core/src/router.ts -B 2 -A 2 echo "" echo "=== Check clearExpiredCache to see how error status affects cache expiration ===" sed -n '2380,2410p' packages/router-core/src/router.ts echo "" echo "=== Look at the lifecycle hook execution (onLeave) ===" sed -n '2140,2170p' packages/router-core/src/router.tsLength of output: 4932
🏁 Script executed:
#!/bin/bash # Check if there are any comments or patterns suggesting notFound should be handled like error for caching echo "=== Search for notFound status handling in context of cache/lifecycle ===" rg -n "notFound" packages/router-core/src/router.ts -B 2 -A 2 | grep -A 2 -B 2 "cache\|Cache\|lifecycle\|onLeave\|onEnter" echo "" echo "=== Check if there's any TODO or FIXME about error/notFound consistency ===" rg -n "TODO|FIXME" packages/router-core/src/router.ts | grep -i "error\|notfound\|status" echo "" echo "=== Verify the complete invalidate flow for context ===" sed -n '2315,2340p' packages/router-core/src/router.tsLength of output: 435
🏁 Script executed:
#!/bin/bash # Get full invalidate method and context echo "=== Full invalidate method (lines 2310-2340) ===" sed -n '2310,2340p' packages/router-core/src/router.ts echo "" echo "=== Check exitingMatches filter logic and any related comments ===" sed -n '2100,2150p' packages/router-core/src/router.ts echo "" echo "=== Search for why error status is special (comments or code patterns) ===" rg -n "error.*cache\|cache.*error" packages/router-core/src/router.ts -i -B 2 -A 2Length of output: 3285
The PR correctly adds
notFoundto invalidation, but should also filter it fromcachedMatchesfor consistency.The change at lines 2321-2323 treats
notFoundlikeerrorduring invalidation (both reset to pending). However, line 2135 only filterserrorfromcachedMatcheswhen routes exit, notnotFound. This creates an inconsistency: error matches never get cached, but notFound matches do, even though they should follow the same pattern during invalidation.Update line 2135 to:
...exitingMatches.filter((d) => d.status !== 'error' && d.status !== 'notFound'),This ensures
notFoundmatches are handled consistently witherrormatches throughout the cache and invalidation lifecycle.🤖 Prompt for AI Agents
packages/router-core/src/router.ts around lines 2135 and 2321-2323: the change added 'notFound' to invalidation handling at ~2321-2323 but the cachedMatches filtering at ~2135 still only excludes 'error' when routes exit, causing inconsistent caching of notFound matches; update the exitingMatches filter at line ~2135 to also exclude d.status === 'notFound' so notFound matches are not cached, making behavior consistent with the invalidation logic that treats notFound like error.✅ Addressed in commits 2794cf0 to a8f1364
birkskyum(GitHub profile, opens in a new tab) added labelsmissing-solid-version
@DeTuksa , can you add a similar test in the solid-router?
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router
birkskyum(GitHub profile, opens in a new tab) removed labelsmissing-solid-version
Sure @birkskyum😀
I added these cases:
it('re-runs loaders that throw notFound() when invalidated via HMR filter', async () => { const history = createMemoryHistory({ initialEntries: ['/hmr-not-found'], }) const loader = vi.fn(() => { throw notFound() }) const rootRoute = createRootRoute({ component: () => <Outlet />, }) const hmrRoute = createRoute({ getParentRoute: () => rootRoute, path: '/hmr-not-found', loader, component: () => <div data-testid="hmr-route">Route</div>, notFoundComponent: () => ( <div data-testid="hmr-route-not-found">Route Not Found</div> ), }) const router = createRouter({ routeTree: rootRoute.addChildren([hmrRoute]), history, }) render(() => <RouterProvider router={router} />) await router.load() await screen.findByTestId('hmr-route-not-found') const initialCalls = loader.mock.calls.length expect(initialCalls).toBeGreaterThan(0) await router.invalidate({ filter: (match) => match.routeId === hmrRoute.id, }) await waitFor(() => expect(loader).toHaveBeenCalledTimes(initialCalls + 1)) await screen.findByTestId('hmr-route-not-found') expect(screen.queryByTestId('hmr-route')).not.toBeInTheDocument() }) it('keeps rendering a route notFoundComponent when loader returns notFound() after invalidate', async () => { const history = createMemoryHistory({ initialEntries: ['/loader-not-found'], }) const loader = vi.fn(() => notFound()) const rootRoute = createRootRoute({ component: () => <Outlet />, }) const loaderRoute = createRoute({ getParentRoute: () => rootRoute, path: '/loader-not-found', loader, component: () => <div data-testid="loader-route">Route</div>, notFoundComponent: () => ( <div data-testid="loader-not-found-component">Route Not Found</div> ), }) const router = createRouter({ routeTree: rootRoute.addChildren([loaderRoute]), history, }) render(() => <RouterProvider router={router} />) await router.load() await screen.findByTestId('loader-not-found-component') const initialCalls = loader.mock.calls.length expect(initialCalls).toBeGreaterThan(0) await router.invalidate() await waitFor(() => expect(loader).toHaveBeenCalledTimes(initialCalls + 1)) await screen.findByTestId('loader-not-found-component') expect(screen.queryByTestId('loader-route')).not.toBeInTheDocument() })@coderabbitai review
✅ Actions performed
Review triggered.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
@birkskyum I think the checks that failed are related to the cloudfare downtime yesterday😅
More templates
- 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
- 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-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-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-start-example-basic-cloudflare
- tanstack-start-example-basic-react-query
- 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/arktype-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5890@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5890@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5890@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5890@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5890@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5890@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5890@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5890@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5890@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5890@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5890@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5890@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5890@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5890@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5890@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5890@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5890@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5890@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5890@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5890@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5890@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5890@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5890@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@5890@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5890@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5890@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5890@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5890@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5890@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5890@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5890@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5890@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5890@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5890@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5890commit:
32a3f09birkskyum(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Walkthrough#
Adds a public RouterCore.invalidate(...) method and updates commit/invalidate logic so matches with status 'notFound' are treated like 'error' during invalidation and commit: errors are cleared and matching exits are reset to 'pending' (optionally via forcePending) so loaders re-run. Adds tests in React and Solid verifying loaders that throw or return notFound() re-run and notFoundComponent remains rendered.
Changes#
packages/router-core/src/router.tsinvalidate(opts?)onRouterCore; commit logic updated to retain/exclude exiting matches consideringstatus === 'error'or'notFound'; invalidate now clears errors and converts'notFound'/'error'matches to'pending'(respectingforcePendingand optionalfilter) so loaders will re-run.packages/react-router/tests/router.test.tsxnotFound(), asserting loaders re-run andnotFoundComponentremains rendered while original route is removed.packages/solid-router/tests/router.test.tsxnotFound(), verifying re-run behavior, rendering ofnotFoundComponent, and loader invocation counts.Sequence Diagram(s)#
Estimated code review effort#
🎯 4 (Complex) | ⏱️ ~45 minutes
packages/router-core/src/router.ts(invalidate API surface, status transitions, cachedMatches commit logic).packages/react-router/tests/router.test.tsxandpackages/solid-router/tests/router.test.tsx(HMR filter simulation and loader invocation counts).invalidatemethod and any exports.Possibly related PRs#
router.invalidate; directly interacts with the new invalidate API.Suggested reviewers#
Poem#
Pre-merge checks and finishing touches#
✅ Passed checks (5 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between c4f892b40108df9b648ee86d2f51b4e81fd208db and 32a3f09d127015ba8cee6353eb83d24fabf40afc.
📒 Files selected for processing (1)
packages/router-core/src/router.ts(3 hunks)🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
📚 Learning: 2025-10-08T08:11:47.088Z
Applied to files:
packages/router-core/src/router.ts📚 Learning: 2025-10-01T18:30:26.591Z
Applied to files:
packages/router-core/src/router.ts🔇 Additional comments (2)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share