fix: handle notFound from params.parse correctly #5864
main fromrefs/pull/5864/head·merged by birkskyum(GitHub profile, opens in a new tab) Summary#
Fixes #5733
Previously, these errors were wrapped in PathParamError, causing a 500 error instead of 404. When notFound() is thrown from params.parse, the router now correctly Sets match status to notFound
Changes#
- Changed paramsError type from PathParamError | undefined to unknown
- NotFoundError and Redirect directly in paramsError
- Added tests in
load.test.tsfor params.parse throwing notFound()
Test Plan#
- params.parse throwing notFound() sets match status to 'notFound' and statusCode to 404
- params.parse with valid input succeeds with status 'success' and statusCode 200
Summary by CodeRabbit#
Bug Fixes
- Enhanced error handling during route parameter parsing to properly distinguish between NotFound, Redirect, and other error types, improving error propagation behavior when route matching fails.
Tests
- Added test coverage for route parameter parsing scenarios, validating correct behavior for both invalid and valid route identifiers in parameter validation.
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core
Actionable comments posted: 1
🧹 Nitpick comments (2)
packages/router-core/tests/load.test.ts (2)
512-570: Consider extracting shared test setup to reduce duplication.Both tests have nearly identical setup code (route creation, router instantiation). This could be refactored into a shared helper function or
beforeEachblock to improve maintainability.Example refactor:
describe('params.parse notFound', () => { const setupRouter = (initialPath: string) => { const rootRoute = new BaseRootRoute({}) const testRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/test/$id', params: { parse: ({ id }: { id: string }) => { const parsed = parseInt(id, 10) if (Number.isNaN(parsed)) { throw notFound() } return { id: parsed } }, }, }) const routeTree = rootRoute.addChildren([testRoute]) const router = new RouterCore({ routeTree, history: createMemoryHistory({ initialEntries: [initialPath] }), }) return { router, testRoute } } test('throws notFound on invalid params', async () => { const { router, testRoute } = setupRouter('/test/invalid') await router.load() const match = router.state.pendingMatches?.find( (m) => m.routeId === testRoute.id, ) expect(match?.status).toBe('notFound') }) test('succeeds on valid params', async () => { const { router, testRoute } = setupRouter('/test/123') await router.load() const match = router.state.matches.find((m) => m.routeId === testRoute.id) expect(match?.status).toBe('success') expect(router.state.statusCode).toBe(200) }) })
512-570: Consider adding test coverage for redirect() in params.parse.The PR changes handle
redirect()thrown fromparams.parseas a special case (similar tonotFound()), but there's no test coverage for this scenario. Adding a test would ensure redirect behavior works correctly.Example test:
test('throws redirect on conditional params', async () => { const rootRoute = new BaseRootRoute({}) const testRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/test/$id', params: { parse: ({ id }: { id: string }) => { if (id === 'redirect-me') { throw redirect({ to: '/other' }) } return { id } }, }, }) const routeTree = rootRoute.addChildren([testRoute]) const router = new RouterCore({ routeTree, history: createMemoryHistory({ initialEntries: ['/test/redirect-me'] }), }) await router.load() expect(router.state.redirect).toBeDefined() })📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between c05679e2afd149e638e3096da9d90c49de18647c and 4e58a0708106e751b2efb1d53ac7d9a6fcfcb289.
📒 Files selected for processing (2)
packages/router-core/src/router.ts(2 hunks)packages/router-core/tests/load.test.ts(1 hunks)
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: FatahChan Repo: TanStack/router PR: 5475 File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0 Timestamp: 2025-10-14T18:59:33.990Z Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.📚 Learning: 2025-10-14T18:59:33.990Z
Learnt from: FatahChan Repo: TanStack/router PR: 5475 File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0 Timestamp: 2025-10-14T18:59:33.990Z Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.Applied to files:
packages/router-core/tests/load.test.tspackages/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/tests/load.test.ts
📚 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
🧬 Code graph analysis (1)
packages/router-core/src/router.ts (2)
packages/router-core/src/index.ts (3)
isNotFound(380-380)isRedirect(374-374)PathParamError(204-204)
packages/router-core/src/redirect.ts (1)
isRedirect(118-120)
🔇 Additional comments (2)
packages/router-core/src/router.ts (2)
1382-1382: Type change enables direct propagation of NotFound and Redirect errors.The type change from
PathParamError | undefinedtounknownis correct. This allowsparamsErrorto holdNotFoundError,Redirect, orPathParamErrorobjects, enabling the router to distinguish between navigation control flow errors (notFound/redirect) and actual parameter validation errors.
1395-1401: Error handling correctly differentiates NotFound/Redirect from validation errors.The updated logic properly handles the three error cases:
NotFoundandRedirecterrors are assigned directly toparamsError, allowing the router to recognize them as navigation control flow- Other errors are wrapped in
PathParamErrorto indicate parameter validation failures
This resolves issue #5733 where
notFound()thrown fromparams.parsewas incorrectly wrapped inPathParamError, resulting in a 500 response instead of 404.packages/router-core/tests/load.test.ts lines 513 to 541@@ -511,0 +521,21 @@521+ if (Number.isNaN(parsed)) {522+ throw notFound()523+ }524+ return { id: parsed }525+ },526+ },527+ })528+ const routeTree = rootRoute.addChildren([testRoute])529+ const router = new RouterCore({530+ routeTree,531+ history: createMemoryHistory({ initialEntries: ['/test/invalid'] }),532+ })533+534+ await router.load()535+536+ const match = router.state.pendingMatches?.find(537+ (m) => m.routeId === testRoute.id,538+ )539+540+ expect(match?.status).toBe('notFound')541+ })⚠️ Potential issue | 🟡 Minor
Add statusCode assertion to verify 404 response.
The test verifies the match status is
'notFound'but doesn't check that the router's statusCode is set to 404. According to the PR objectives, this test should verify both the match status and the statusCode.Add this assertion after line 540:
expect(match?.status).toBe('notFound') +expect(router.state.statusCode).toBe(404)📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
test('throws notFound on invalid params', async () => { const rootRoute = new BaseRootRoute({}) const testRoute = new BaseRoute({ getParentRoute: () => rootRoute, path: '/test/$id', params: { parse: ({ id }: { id: string }) => { const parsed = parseInt(id, 10) if (Number.isNaN(parsed)) { throw notFound() } return { id: parsed } }, }, }) const routeTree = rootRoute.addChildren([testRoute]) const router = new RouterCore({ routeTree, history: createMemoryHistory({ initialEntries: ['/test/invalid'] }), }) await router.load() const match = router.state.pendingMatches?.find( (m) => m.routeId === testRoute.id, ) expect(match?.status).toBe('notFound') expect(router.state.statusCode).toBe(404) })🤖 Prompt for AI Agents
In packages/router-core/tests/load.test.ts around lines 513 to 541, the test checks that the match status is 'notFound' but doesn't assert the router's overall statusCode; add an assertion after the existing expect(match?.status).toBe('notFound') to also expect router.statusCode to equal 404 so the test verifies both the match status and the router's 404 statusCode.View your CI Pipeline Execution ↗ for commit 4e58a0708106e751b2efb1d53ac7d9a6fcfcb289
Command Status Duration Result nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded 9m 16s View ↗ nx run-many --target=build --exclude=examples/*...✅ Succeeded 1m 27s View ↗
☁️ Nx Cloud last updated this comment at
2025-11-19 16:10:38UTCMore templates
- 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-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/arktype-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5864@tanstack/directive-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5864@tanstack/eslint-plugin-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5864@tanstack/history
npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5864@tanstack/nitro-v2-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/nitro-v2-vite-plugin@5864@tanstack/react-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5864@tanstack/react-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5864@tanstack/react-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5864@tanstack/react-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5864@tanstack/react-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5864@tanstack/react-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5864@tanstack/router-cli
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5864@tanstack/router-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5864@tanstack/router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5864@tanstack/router-devtools-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5864@tanstack/router-generator
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5864@tanstack/router-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5864@tanstack/router-ssr-query-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5864@tanstack/router-utils
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5864@tanstack/router-vite-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5864@tanstack/server-functions-plugin
npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5864@tanstack/solid-router
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5864@tanstack/solid-router-devtools
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5864@tanstack/solid-router-ssr-query
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-ssr-query@5864@tanstack/solid-start
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5864@tanstack/solid-start-client
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5864@tanstack/solid-start-server
npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5864@tanstack/start-client-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5864@tanstack/start-plugin-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5864@tanstack/start-server-core
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5864@tanstack/start-static-server-functions
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-static-server-functions@5864@tanstack/start-storage-context
npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5864@tanstack/valibot-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5864@tanstack/virtual-file-routes
npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5864@tanstack/zod-adapter
npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5864commit:
4e58a07birkskyum(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
Walkthrough#
Modifies path-parameter error handling in RouterCore to propagate NotFound and Redirect errors directly from params.parse, while wrapping other errors in PathParamError. Updates paramsError type from
PathParamError | undefinedtounknown. Adds test coverage for notFound behavior during param parsing.Changes#
packages/router-core/src/router.tsPathParamError | undefinedtounknown.packages/router-core/tests/load.test.tsSequence Diagram#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~25 minutes
paramsError: unknownrequires verification of all code paths consuming this variablePossibly related PRs#
Suggested labels#
package: router-coreSuggested reviewers#
Poem#
Pre-merge checks and finishing touches#
❌ Failed checks (1 warning)
@coderabbitai generate docstringsto improve docstring coverage.✅ Passed checks (4 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment `@coderabbitai help` to get the list of available commands and usage tips.