Skip to content
Source
Sign inSign up
TanStack/router

refactor(router-core): flatten loadMatches #4961

MergedSheraff(GitHub profile, opens in a new tab)merged 7 commits intomain fromrefs/pull/4961/headmerged by Sheraff(GitHub profile, opens in a new tab)

This PR should be a no-op. Just restructuring the code to have all the functions used by loadMatches at the same level, instead of nested callbacks. In order to still have access to the data that was previously in scope because of nesting, we use a innerLoadContext object, which is basically just the arguments of loadMatches, and a few mutables.

However, in order to do so, we have to rearrange promises in an area that is sensitive to any microtask order change, and we did change some of them. So this is not really a no-op, even though this does not attempt any optimization.

Summary by CodeRabbit

  • New Features
    • Smoother navigations with predictable pending states and minimum display durations.
    • More consistent head/meta updates after route loading.
  • Bug Fixes
    • More reliable redirects and 404 handling, including during preloading and SSR.
    • Reduced UI flicker by refining pending and preloading behavior.
  • Refactor
    • Reworked the routing load pipeline for improved performance, stability, and SSR behavior.
    • Streamlined before-load steps for clearer, more consistent execution.
  • Tests
    • Updated tests to reflect the new loading flow.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: router-core

    2. View your CI Pipeline Execution ↗ for commit 4e8d69e235bfc2e09ed6ebd6f1900a305e2e3997

      CommandStatusDurationResult
      nx affected --targets=test:eslint,test:unit,tes...✅ Succeeded5m 11sView ↗
      nx run-many --target=build --exclude=examples/*...✅ Succeeded1m 32sView ↗

      ☁️ Nx Cloud last updated this comment at 2025-08-15 20:53:33 UTC

    3. More templates

      @tanstack/arktype-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@4961

      @tanstack/directive-functions-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@4961

      @tanstack/eslint-plugin-router

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

      @tanstack/history

      npm i https://pkg.pr.new/TanStack/router/@tanstack/history@4961

      @tanstack/react-router

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

      @tanstack/react-router-devtools

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

      @tanstack/react-router-ssr-query

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

      @tanstack/react-start

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@4961

      @tanstack/react-start-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@4961

      @tanstack/react-start-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@4961

      @tanstack/react-start-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@4961

      @tanstack/router-cli

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

      @tanstack/router-core

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

      @tanstack/router-devtools

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

      @tanstack/router-devtools-core

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

      @tanstack/router-generator

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

      @tanstack/router-plugin

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

      @tanstack/router-ssr-query-core

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

      @tanstack/router-utils

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

      @tanstack/router-vite-plugin

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

      @tanstack/server-functions-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@4961

      @tanstack/solid-router

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

      @tanstack/solid-router-devtools

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

      @tanstack/solid-start

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@4961

      @tanstack/solid-start-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@4961

      @tanstack/solid-start-plugin

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@4961

      @tanstack/solid-start-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@4961

      @tanstack/start-client-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@4961

      @tanstack/start-plugin-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@4961

      @tanstack/start-server-core

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@4961

      @tanstack/start-server-functions-client

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@4961

      @tanstack/start-server-functions-fetcher

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@4961

      @tanstack/start-server-functions-server

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@4961

      @tanstack/start-storage-context

      npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@4961

      @tanstack/valibot-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@4961

      @tanstack/virtual-file-routes

      npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@4961

      @tanstack/zod-adapter

      npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@4961

      commit: 4e8d69e

    4. Walkthrough

      Refactors router loading into a context-driven pipeline using InnerLoadContext, replaces the old loadMatches signature with a baseContext parameter, adds many private helpers for beforeLoad/loader/head/pending/redirect/notFound flows, and updates a Solid test to await router.latestLoadPromise instead of calling router.load().

      Changes

      Cohort / File(s)Summary
      Router core loading refactor
      packages/router-core/src/router.ts
      Replaces monolithic loadMatches with an InnerLoadContext-driven pipeline. Changes public loadMatches signature to accept a single baseContext. Adds many private helpers (triggerOnReady, resolvePreload, handleRedirectAndNotFound, shouldSkipLoader, isBeforeLoadSsr, setupPendingTimeout, executeBeforeLoad, executeHead, runLoader, loadRouteMatch, etc.). Centralizes redirect/notFound handling, integrates pending/min-pending timing, separates beforeLoad and loader/head steps, adjusts SSR/hydration behavior, and replaces _handleNotFound to accept InnerLoadContext. Adds makeMaybe helper.
      Solid router test adjustment
      packages/solid-router/tests/Transitioner.test.tsx
      Removes explicit router.load() before render; renders RouterProvider then awaits router.latestLoadPromise; updates spy expectations for load call counts; maintains loader mock verification and restores spy.

      Sequence Diagram(s)

      sequenceDiagram
        participant App
        participant RouterCore
        participant InnerLoadContext as Context
        participant Matches
        participant BeforeLoad
        participant Loader
        participant Head
        participant ErrorHandling as Redirect/NotFound
      
        App->>RouterCore: loadMatches(baseContext)
        RouterCore->>RouterCore: create InnerLoadContext
        RouterCore->>Context: resolvePreload / triggerOnReady
        RouterCore->>RouterCore: handleRedirectAndNotFound (early checks)
        RouterCore->>BeforeLoad: executeBeforeLoad (serial for matches)
        alt redirect/notFound
          BeforeLoad->>ErrorHandling: signal redirect/notFound
          ErrorHandling-->>RouterCore: handled/converted
        else proceed
          RouterCore->>RouterCore: setupPendingTimeout / min-pending
          RouterCore->>Matches: loadRouteMatch (parallel up to first bad)
          Matches->>Loader: runLoader (loader + beforeLoad promises)
          Loader-->>Matches: data / error
          Matches->>Head: executeHead
          Head-->>RouterCore: metadata
          RouterCore->>Context: updateMatch per match
          RouterCore-->>App: return resolved matches
        end

      Estimated code review effort

      🎯 3 (Moderate) | ⏱️ ~20 minutes

      Poem

      I hop through routes with bright intent, Inner contexts guide each bent. Before-load whispers, loaders hum, Pending moments softly drum. Redirects twirl — I skip, I track, NotFound nibbles? I bounce right back. 🥕🐇

      Tip

      🔌 Remote MCP (Model Context Protocol) integration is now available!

      Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


      📜 Recent review details

      Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro

      💡 Knowledge Base configuration:

      • MCP integration is disabled by default for public repositories
      • Jira integration is disabled by default for public repositories
      • Linear integration is disabled by default for public repositories

      You can enable these sources in your CodeRabbit configuration.

      📥 Commits

      Reviewing files that changed from the base of the PR and between 205a663fa276e74ce1fbc8c2854855f4c8d86731 and 4e8d69e235bfc2e09ed6ebd6f1900a305e2e3997.

      📒 Files selected for processing (1)
      • packages/router-core/src/router.ts (6 hunks)
      🧰 Additional context used
      🧬 Code Graph Analysis (1)
      packages/router-core/src/router.ts (6)
      packages/router-core/src/index.ts (10)
      • ParsedLocation (70-70)
      • AnyRouteMatch (88-88)
      • isRedirect (372-372)
      • AnyRoute (161-161)
      • rootRouteId (109-109)
      • createControlledPromise (278-278)
      • BeforeLoadContextOptions (179-179)
      • ControlledPromise (301-301)
      • LoaderFnContext (174-174)
      • MakeRouteMatch (87-87)
      packages/router-core/src/location.ts (1)
      • ParsedLocation (4-13)
      packages/router-core/src/Matches.ts (2)
      • AnyRouteMatch (239-239)
      • MakeRouteMatch (217-237)
      packages/router-core/src/redirect.ts (1)
      • isRedirect (95-97)
      packages/router-core/src/root.ts (1)
      • rootRouteId (1-1)
      packages/router-core/src/utils.ts (3)
      • isPromise (477-485)
      • createControlledPromise (398-422)
      • ControlledPromise (391-396)
      ⏰ 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: Test
      • GitHub Check: Preview
      🔇 Additional comments (19)
      packages/router-core/src/router.ts (19)

      766-776: Well-structured InnerLoadContext type definition.

      The InnerLoadContext type properly encapsulates all the necessary data for the flattened loadMatches implementation. The type includes the original function parameters and mutable state like firstBadMatchIndex and matchPromises which are needed for the new context-driven approach.


      2098-2105: Clean helper method for triggering onReady callback.

      The triggerOnReady method properly checks the rendered state before calling the callback and handles both synchronous and asynchronous return values correctly.


      2107-2115: Clear preload resolution logic.

      The resolvePreload method efficiently determines if a match should be treated as preload by checking both the context flag and whether the match is already loaded.


      2117-2161: Comprehensive redirect and not found error handling.

      The handleRedirectAndNotFound method centralizes error handling logic effectively. It properly manages promise resolution, updates match status, and handles the different error types with appropriate transformations.


      2163-2176: Appropriate loader skip conditions.

      The shouldSkipLoader method correctly identifies when to skip loader execution based on dehydration state and SSR configuration.


      2178-2227: Robust error handling with proper context updates.

      The handleSerialError method provides comprehensive error handling that includes promise management, match updates, and proper error propagation through the route's error handler.


      2229-2298: Thorough SSR determination logic.

      The isBeforeLoadSsr method handles all the SSR scenarios correctly, including shell mode, parent overrides, and function-based SSR determination with proper promise handling.


      2300-2329: Well-implemented pending timeout setup.

      The setupPendingTimeout method properly configures pending component display timing with appropriate checks for server-side rendering and preload conditions.


      2331-2366: Efficient beforeLoad execution control.

      The shouldExecuteBeforeLoad method effectively determines when to execute beforeLoad by checking existing promises and handling various match states appropriately.


      2368-2500: Comprehensive beforeLoad execution with proper error handling.

      The executeBeforeLoad method handles all aspects of beforeLoad execution including promise management, context setup, error handling, and proper cleanup.


      2502-2544: Well-structured beforeLoad orchestration.

      The handleBeforeLoad method properly orchestrates SSR determination and beforeLoad execution with clear separation of concerns and proper promise chaining.


      2546-2594: Clean head execution implementation.

      The executeHead method efficiently handles head-related content generation with proper null checks and promise coordination for meta, scripts, and headers.


      2596-2601: Simple and effective pending promise resolution.

      The potentialPendingMinPromise method provides a clean way to access minimum pending promises for timing control.


      2603-2628: Comprehensive loader context creation.

      The getLoaderContext method properly constructs the loader context with all necessary properties including parent promises, navigation methods, and proper preload handling.


      2630-2756: Robust loader execution with comprehensive error handling.

      The runLoader method handles all aspects of loader execution including chunk loading, result processing, head execution, and proper error handling with promise coordination.


      2758-2889: Sophisticated route match loading with stale-while-revalidate.

      The loadRouteMatch method implements complex caching and revalidation logic properly, handling various scenarios like async loading, stale data, and proper promise management.


      2891-2951: Well-structured loadMatches refactor maintaining backward compatibility.

      The new loadMatches method successfully flattens the nested structure while preserving all functionality. The method properly:

      1. Initializes the InnerLoadContext with defaults
      2. Handles hydration scenarios with pending component rendering
      3. Executes beforeLoad operations serially
      4. Runs route loading in parallel up to the first bad match
      5. Maintains proper error handling and promise coordination

      The implementation preserves the original behavior while improving code organization and maintainability.


      3224-3274: Updated _handleNotFound signature properly uses context.

      The _handleNotFound method has been correctly updated to use InnerLoadContext instead of individual parameters, maintaining the same functionality while aligning with the new context-driven approach.


      3287-3295: Useful utility function for error handling.

      The makeMaybe helper function provides a clean way to wrap values with error states, which is particularly useful for SSR context creation where errors need to be handled gracefully.

      ✨ Finishing Touches
      • 📝 Generate Docstrings
        🧪 Generate unit tests
      • Create PR with unit tests
      • Post copyable unit tests in a comment
      • Commit unit tests in branch `refactor-router-core-flatten-load-matches`

      🪧 Tips

      Chat

      There are 3 ways to chat with CodeRabbit:

      • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
        • I pushed a fix in commit <commit_id>, please review it.
        • Open a follow-up GitHub issue for this discussion.
      • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
      • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
        • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
        • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

      Support

      Need help? Create a ticket on our support page for assistance with any issues or questions.

      CodeRabbit Commands (Invoked using PR/Issue comments)

      Type @coderabbitai help to get the list of available commands.

      Other keywords and placeholders

      • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
      • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
      • Add @coderabbitai anywhere in the PR title to generate the title automatically.

      CodeRabbit Configuration File (.coderabbit.yaml)

      • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
      • Please see the configuration documentation for more information.
      • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

      Status, Documentation and Community

      • Visit our Status Page to check the current availability of CodeRabbit.
      • Visit our Documentation for detailed information on how to use CodeRabbit.
      • Join our Discord Community to get help, request features, and share feedback.
      • Follow us on X/Twitter for updates and announcements.
    5. github-actions[bot](GitHub profile, opens in a new tab) added labelspackage: solid-router

    6. Actionable comments posted: 0

      🧹 Nitpick comments (4)
      packages/router-core/src/router.ts (4)

      2098-2103: Consider extracting the rendered flag logic.

      The triggerOnReady method has a side effect of setting rendered = true. Consider documenting why this flag is needed and its relationship to the loading lifecycle, as it's not immediately clear from the method name.

       private triggerOnReady = async (innerLoadContext: InnerLoadContext) => {
      +  // Mark as rendered to prevent duplicate onReady calls during the same load cycle
         if (!innerLoadContext.rendered) {
           innerLoadContext.rendered = true
           await innerLoadContext.onReady?.()
         }
       }

      2176-2225: Consider consistent error property assignment.

      In handleSerialError, the routerCode is assigned directly to the error object. Consider using a more type-safe approach or documenting this property addition.

      -  err.routerCode = routerCode
      +  // Attach router-specific error code for debugging
      +  Object.defineProperty(err, 'routerCode', {
      +    value: routerCode,
      +    writable: false,
      +    enumerable: true,
      +    configurable: false
      +  })

      2276-2281: Consider extracting the makeMaybe helper to utils.

      The makeMaybe function at the bottom of the file seems like a general utility that could be moved to the utils module for better organization and potential reuse.

      Move the makeMaybe function to the utils module:

      // In utils.ts
      export function makeMaybe<T>(value: T, error: any): 
        | { status: 'success'; value: T }
        | { status: 'error'; error: any } {
        if (error) {
          return { status: 'error', error }
        }
        return { status: 'success', value }
      }

      2227-2296: SSR handling logic is well-structured but could benefit from documentation.

      The isBeforeLoadSsr method handles complex SSR inheritance logic. Consider adding JSDoc comments to explain the inheritance rules, especially the parent override logic and the 'data-only' mode behavior.

      +/**
      + * Determines SSR mode for a route match, inheriting from parent matches
      + * and respecting configuration hierarchy.
      + * 
      + * SSR modes:
      + * - true: Full SSR
      + * - 'data-only': SSR data but not components  
      + * - false: No SSR
      + * 
      + * Inheritance rules:
      + * - Shell mode: only SSR root route
      + * - Parent false: children inherit false
      + * - Parent 'data-only': children with true become 'data-only'
      + */
       private isBeforeLoadSsr = async (
         innerLoadContext: InnerLoadContext,
         matchId: string,
         index: number,
         route: AnyRoute,
       ) => {
      📜 Review details

      Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro

      💡 Knowledge Base configuration:

      • MCP integration is disabled by default for public repositories
      • Jira integration is disabled by default for public repositories
      • Linear integration is disabled by default for public repositories

      You can enable these sources in your CodeRabbit configuration.

      📥 Commits

      Reviewing files that changed from the base of the PR and between 0df9067bcc008e876cac9ac5a284bc0c01efc8ec and 205a663fa276e74ce1fbc8c2854855f4c8d86731.

      📒 Files selected for processing (2)
      • packages/router-core/src/router.ts (6 hunks)
      • packages/solid-router/tests/Transitioner.test.tsx (1 hunks)
      🧰 Additional context used
      🧬 Code Graph Analysis (1)
      packages/router-core/src/router.ts (6)
      packages/router-core/src/index.ts (10)
      • ParsedLocation (70-70)
      • AnyRouteMatch (88-88)
      • isRedirect (372-372)
      • AnyRoute (161-161)
      • rootRouteId (109-109)
      • createControlledPromise (278-278)
      • BeforeLoadContextOptions (179-179)
      • LoaderFnContext (174-174)
      • MakeRouteMatch (87-87)
      • NotFoundError (377-377)
      packages/router-core/src/location.ts (1)
      • ParsedLocation (4-13)
      packages/router-core/src/Matches.ts (2)
      • AnyRouteMatch (239-239)
      • MakeRouteMatch (217-237)
      packages/router-core/src/redirect.ts (1)
      • isRedirect (95-97)
      packages/router-core/src/root.ts (1)
      • rootRouteId (1-1)
      packages/router-core/src/utils.ts (1)
      • createControlledPromise (398-422)
      🔇 Additional comments (6)
      packages/solid-router/tests/Transitioner.test.tsx (2)

      33-34: Test now aligns with new router loading pipeline.

      The switch from explicit router.load() to using router.latestLoadPromise correctly leverages the new context-driven loading flow coordinated by the RouterProvider. This change is consistent with the router-core refactoring that moved loading orchestration into a pipeline-based approach.


      38-38: All loadSpy expectations correctly updated to a single call Verified that in both the client and server Transitioner.test.tsx files, loadSpy is now asserted with toHaveBeenCalledTimes(1), and there are no remaining tests expecting two calls. This aligns with the refactored behavior where the RouterProvider handles the initial load automatically on the client and does not trigger an extra load on the server. No further changes needed.

      packages/router-core/src/router.ts (4)

      766-776: Well-structured context object for the loading pipeline.

      The InnerLoadContext type effectively encapsulates all the state needed for the refactored loading pipeline. The inclusion of firstBadMatchIndex, matchPromises, and other fields provides clean separation of concerns and makes the loading flow more maintainable.


      2119-2159: Comprehensive error handling with proper cleanup.

      The handleRedirectAndNotFound method properly handles both redirect and not-found cases, ensuring promises are resolved and match states are updated correctly. The distinction between handling during preload vs regular load is well-considered.


      2500-2542: Clean separation of concerns in beforeLoad handling.

      The handleBeforeLoad method effectively orchestrates the SSR determination, skip checks, and execution flow. The chain of responsibility pattern with serverSsr → queueExecution → execute is well-structured.


      2882-2940: Excellent refactoring of loadMatches with serial/parallel execution.

      The refactored loadMatches method clearly separates serial execution of beforeLoad handlers from parallel execution of loaders. The use of innerLoadContext to maintain state throughout the pipeline is clean and maintainable. The error handling for NotFound and Redirect exceptions is comprehensive.

Sign in to join this conversation.