Skip to content
Source
Sign inSign up
TanStack/router

fix(router-core): handle rejected promise in loadRouteChunk #6645

Openzhuangya(GitHub profile, opens in a new tab)wants to merge 3 commits intomain fromrefs/pull/6645/headopened

Summary

loadRouteChunk calls route.lazyFn() without a .catch(), creating an unhandled promise rejection when the dynamic import fails (e.g. network error, stale chunk after deploy).

This is harmless to end users because lazyRouteComponent independently retries and recovers via window.location.reload(), but the unhandled rejection floods error monitoring tools (Sentry, etc.) with noise.

Fixes #6107

What this PR does

Adds a .catch() handler to the lazyFn() promise chain in loadRouteChunk that:

  1. Marks the rejection as handled — prevents unhandledrejection events
  2. Clears _lazyPromise — allows the route to be retried on the next navigation attempt

What this PR does NOT do

  • Does not re-throw the error (unsafe — _lazyPromise is consumed via .then() at L1016 in loadRouteChunkComponents, which would create a new unhandled rejection)
  • Does not change match status to 'error' — preserving existing behavior where lazyRouteComponent's auto-reload handles recovery
  • Does not modify any other code paths

Why .catch() only (no re-throw)?

_lazyPromise is consumed in two places:

  1. L683: await route._lazyPromise — inside try/catch, can handle rejections ✓
  2. L1016: route._lazyPromise.then(loadComponents) — no .catch(), re-throwing would create a new unhandled rejection ✗

The minimal .catch() approach handles the rejection without introducing new failure modes.

Testing

  • Added 2 new tests (33 total, all passing):
    • Verifies no unhandledrejection when lazyFn fails + _lazyPromise cleanup
    • Verifies normal success path still works correctly

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling for lazy-loaded routes: failed lazy loads now clear their failed state, avoid unhandled promise rejections, and can be retried on subsequent navigation attempts.
  • Tests

    • Added comprehensive tests covering lazy route loading success, failure, and retry flows to ensure proper state reset, error handling, and component resolution.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      📝 Walkthrough

      Walkthrough

      Adds handling for rejected lazy-route promises in loadRouteChunk: failed lazyFn now clears the route's _lazyPromise and prevents unhandled rejections, allowing retries. Successful lazy resolution behavior (merging lazy options, marking _lazyLoaded) is preserved.

      Changes

      Cohort / File(s)Summary
      Lazy route loader
      packages/router-core/src/load-matches.ts
      Adds a .catch() to the lazy-route promise chain to clear route._lazyPromise on rejection, gating component loading on route._lazyLoaded and allowing retry after failure.
      Tests
      packages/router-core/tests/load.test.ts
      Adds tests for lazy load failure, success, and retry paths; asserts no unhandledRejection, proper cleanup of _lazyPromise, _lazyLoaded flag behavior, and components loading state.

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~20 minutes

      Suggested reviewers

      • schiller-manuel

      Poem

      🐰 I nibble on a broken thread, A promise tripped and bowed its head. Now caught with care, it clears away, And tries again another day. 🥕🔁✨

      🚥 Pre-merge checks | ✅ 5 | ❌ 1
      ❌ Failed checks (1 warning)
      Check nameStatusExplanationResolution
      Docstring Coverage⚠️ WarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%.Write docstrings for the functions missing them to satisfy the coverage threshold.
      ✅ Passed checks (5 passed)
      Check nameStatusExplanation
      Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
      Title check✅ PassedThe title accurately summarizes the main change: adding promise rejection handling in loadRouteChunk.
      Linked Issues check✅ PassedThe PR directly addresses issue #6107 by implementing a .catch() handler to prevent unhandled rejections from failed dynamic imports and allowing retry on subsequent navigation.
      Out of Scope Changes check✅ PassedAll changes are focused on handling rejected promises in loadRouteChunk with corresponding tests; no unrelated modifications detected.
      Merge Conflict Detection✅ Passed✅ No merge conflicts detected when merging into main
      ✏️ Tip: You can configure your own custom pre-merge checks in the settings.
      ✨ Finishing touches
      • 📝 Generate docstrings
        🧪 Generate unit tests (beta)
      • Create PR with unit tests
      • Post copyable unit tests in a comment

      No actionable comments were generated in the recent review. 🎉

      🧹 Recent nitpick comments
      packages/router-core/tests/load.test.ts (1)

      804-850: Listener leak if an assertion throws before removeListener.

      In both the failure test and the retry test, process.removeListener is only reached on the happy path. If any expect fails (or loadRouteChunk unexpectedly rejects), the listener stays registered and can cause false positives/negatives in subsequent tests. Wrapping in try/finally (or using vitest's onTestFinished) would make this robust.

      ♻️ Suggested pattern (applied to the first test; same idea for the retry test)
         test('should not produce unhandled rejection when lazyFn fails', async () => {
           const unhandledRejection = vi.fn()
           process.on('unhandledRejection', unhandledRejection)
      +    // Ensure cleanup even if the test throws
      +    onTestFinished(() => process.removeListener('unhandledRejection', unhandledRejection))
       
           ...
       
           expect(unhandledRejection).not.toHaveBeenCalled()
      -
      -    process.removeListener('unhandledRejection', unhandledRejection)
         })

      You'd import onTestFinished from vitest:

      import { describe, expect, onTestFinished, test, vi } from 'vitest'

      Also applies to: 888-940


      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
      Comment `@coderabbitai help` to get the list of available commands and usage tips.
    3. Actionable comments posted: 1

      🤖 Fix all issues with AI agents
      In `@packages/router-core/src/load-matches.ts`:
      - Around line 985-989: The catch block that currently only clears
      route._lazyPromise should also reset route._componentsLoaded = false and
      route._componentsPromise = undefined to allow retries, and then rethrow the
      caught error so the promise chain doesn't continue into the subsequent
      .then(loadComponents) path; update the .catch(() => { ... }) handler to restore
      those route fields (route._lazyPromise, route._componentsLoaded,
      route._componentsPromise) and throw the original error.
      🧹 Nitpick comments (1)
      packages/router-core/tests/load.test.ts (1)

      804-847: Consider adding a retry-after-failure test to catch the _componentsLoaded stale-state bug.

      This test verifies the unhandled rejection is suppressed and _lazyPromise is cleared, but it doesn't verify that a subsequent call to loadRouteChunk (simulating retry with a succeeding lazyFn) actually works end-to-end. Given the _componentsLoaded issue noted in the source, a retry test would have caught it.

      Also consider asserting (fooRoute as any)._componentsLoaded is false after the failed load to ensure full cleanup.

    4. ✅ 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.

    5. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit 5ebfd2a9b5e304dc4317e5f91a9c4c945cf79e8c

      CommandStatusDurationResult
      nx run tanstack-router-e2e-bundle-size:build --...✅ Succeeded1m 28sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-03-19 22:54:56 UTC

    6. More templates

      @tanstack/arktype-adapter

      npm i https://pkg.pr.new/@tanstack/arktype-adapter@6645

      @tanstack/eslint-plugin-router

      npm i https://pkg.pr.new/@tanstack/eslint-plugin-router@6645

      @tanstack/history

      npm i https://pkg.pr.new/@tanstack/history@6645

      @tanstack/nitro-v2-vite-plugin

      npm i https://pkg.pr.new/@tanstack/nitro-v2-vite-plugin@6645

      @tanstack/react-router

      npm i https://pkg.pr.new/@tanstack/react-router@6645

      @tanstack/react-router-devtools

      npm i https://pkg.pr.new/@tanstack/react-router-devtools@6645

      @tanstack/react-router-ssr-query

      npm i https://pkg.pr.new/@tanstack/react-router-ssr-query@6645

      @tanstack/react-start

      npm i https://pkg.pr.new/@tanstack/react-start@6645

      @tanstack/react-start-client

      npm i https://pkg.pr.new/@tanstack/react-start-client@6645

      @tanstack/react-start-server

      npm i https://pkg.pr.new/@tanstack/react-start-server@6645

      @tanstack/router-cli

      npm i https://pkg.pr.new/@tanstack/router-cli@6645

      @tanstack/router-core

      npm i https://pkg.pr.new/@tanstack/router-core@6645

      @tanstack/router-devtools

      npm i https://pkg.pr.new/@tanstack/router-devtools@6645

      @tanstack/router-devtools-core

      npm i https://pkg.pr.new/@tanstack/router-devtools-core@6645

      @tanstack/router-generator

      npm i https://pkg.pr.new/@tanstack/router-generator@6645

      @tanstack/router-plugin

      npm i https://pkg.pr.new/@tanstack/router-plugin@6645

      @tanstack/router-ssr-query-core

      npm i https://pkg.pr.new/@tanstack/router-ssr-query-core@6645

      @tanstack/router-utils

      npm i https://pkg.pr.new/@tanstack/router-utils@6645

      @tanstack/router-vite-plugin

      npm i https://pkg.pr.new/@tanstack/router-vite-plugin@6645

      @tanstack/solid-router

      npm i https://pkg.pr.new/@tanstack/solid-router@6645

      @tanstack/solid-router-devtools

      npm i https://pkg.pr.new/@tanstack/solid-router-devtools@6645

      @tanstack/solid-router-ssr-query

      npm i https://pkg.pr.new/@tanstack/solid-router-ssr-query@6645

      @tanstack/solid-start

      npm i https://pkg.pr.new/@tanstack/solid-start@6645

      @tanstack/solid-start-client

      npm i https://pkg.pr.new/@tanstack/solid-start-client@6645

      @tanstack/solid-start-server

      npm i https://pkg.pr.new/@tanstack/solid-start-server@6645

      @tanstack/start-client-core

      npm i https://pkg.pr.new/@tanstack/start-client-core@6645

      @tanstack/start-fn-stubs

      npm i https://pkg.pr.new/@tanstack/start-fn-stubs@6645

      @tanstack/start-plugin-core

      npm i https://pkg.pr.new/@tanstack/start-plugin-core@6645

      @tanstack/start-server-core

      npm i https://pkg.pr.new/@tanstack/start-server-core@6645

      @tanstack/start-static-server-functions

      npm i https://pkg.pr.new/@tanstack/start-static-server-functions@6645

      @tanstack/start-storage-context

      npm i https://pkg.pr.new/@tanstack/start-storage-context@6645

      @tanstack/valibot-adapter

      npm i https://pkg.pr.new/@tanstack/valibot-adapter@6645

      @tanstack/virtual-file-routes

      npm i https://pkg.pr.new/@tanstack/virtual-file-routes@6645

      @tanstack/vue-router

      npm i https://pkg.pr.new/@tanstack/vue-router@6645

      @tanstack/vue-router-devtools

      npm i https://pkg.pr.new/@tanstack/vue-router-devtools@6645

      @tanstack/vue-router-ssr-query

      npm i https://pkg.pr.new/@tanstack/vue-router-ssr-query@6645

      @tanstack/vue-start

      npm i https://pkg.pr.new/@tanstack/vue-start@6645

      @tanstack/vue-start-client

      npm i https://pkg.pr.new/@tanstack/vue-start-client@6645

      @tanstack/vue-start-server

      npm i https://pkg.pr.new/@tanstack/vue-start-server@6645

      @tanstack/zod-adapter

      npm i https://pkg.pr.new/@tanstack/zod-adapter@6645

      commit: 5ebfd2a

    7. Would be good to get this in, having to work around this error showing up in Sentry

Sign in to join this conversation.