Skip to content

test(react-router): throw redirect during preload #4976

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

Sheraff
Copy link
Contributor

@Sheraff Sheraff commented Aug 17, 2025

Add a test to validate the following behavior: a redirect throw suring preload evicts the match from the cache before actual load.

I'm not 100% sure this is the behavior we want, but this is the current behavior.

The actual goal is to figure out what the onUpdate callback on the __store is used for. I would like to remove it because this seems pretty heavy.

Summary by CodeRabbit

  • Tests
    • Added SPA coverage for a redirect thrown during preload, verifying protected-route preloading, hook invocation order, and that preload redirects don’t block eventual navigation after sign-in.
  • Chores / Refactor
    • Internal routing behavior updated to simplify store/update handling and introduce an internal routing flag; no user-facing API changes.

Copy link

coderabbitai bot commented Aug 17, 2025

Walkthrough

Adds a test verifying that a route that throws redirect() during preload does not block a later successful navigation after sign-in, and introduces an internal _buildLocation flag on MatchRoutesOpts plus removal of an onUpdate store handler in router-core.

Changes

Cohort / File(s) Summary
React Router Tests – Redirect Preload
packages/react-router/tests/redirect.test.tsx
Adds test "when redirect is thrown during preload": protected route beforeLoad calls mocks and conditionally throws redirect({ to: '/login' }) when signed-out; simulates preload via focus, flips auth to signed-in, navigates, and asserts final location and mock call counts.
Router Core – Internal API & Store Update
packages/router-core/src/router.ts
Adds internal optional flag _buildLocation?: boolean to MatchRoutesOpts and removes/commented-out the onUpdate handler passed to Store in RouterCore.update that filtered out cachedMatches with status 'redirected'.

Sequence Diagram(s)

sequenceDiagram
  actor User
  participant App as App/Router
  participant Route as Protected.beforeLoad
  participant Auth as AuthState
  participant Redirect as redirect()

  User->>App: Focus link to /protected (preload intent)
  App->>Route: beforeLoad (preload)
  Route->>Auth: Check signedIn -> false
  Route->>Redirect: throw redirect('/login')
  App-->>User: Preload handled (no navigation)

  User->>Auth: Sign in (true)
  User->>App: Navigate to /protected
  App->>Route: beforeLoad (navigation)
  Route->>Auth: Check signedIn -> true
  Route-->>App: Continue (afterRedirectMock invoked)
  App-->>User: Show Protected (/protected)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

package: router-core

Suggested reviewers

  • schiller-manuel

Poem

I twitched to preload, hop-hop—redirect!
A login burrow blocked my path, unchecked.
Then nibble of state—now signed in, hooray!
I bound to Protected, carrot-bright day. 🥕🐇


📜 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 6a23244 and 8a18a9f.

📒 Files selected for processing (1)
  • packages/router-core/src/router.ts (2 hunks)
⏰ 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 (2)
packages/router-core/src/router.ts (2)

911-922: Remove dead Store.onUpdate block; optionally drop empty options argument

The commented onUpdate handler in packages/router-core/src/router.ts (lines 911–922) is no longer needed—stale matches are already pruned in beforeLoad. Remove the entire commented block. If the Store constructor’s second argument is optional in your @tanstack/store version, you can also delete the {}; otherwise, keep it.

• File: packages/router-core/src/router.ts
Lines 911–922
• Suggested diff:

-      this.__store = new Store(getInitialRouterState(this.latestLocation), {
-        // onUpdate: () => {
-        //   this.__store.state = {
-        //     ...this.state,
-        //     cachedMatches: this.state.cachedMatches.filter(
-        //       (d) => !['redirected'].includes(d.status),
-        //     ),
-        //   }
-        // },
-      })
+      this.__store = new Store(getInitialRouterState(this.latestLocation))

Please confirm whether the Store constructor’s options parameter is optional; if not, retain an empty {} instead.


510-513: Constrain and hide the internal flag to avoid accidental external use

Tighten _buildLocation to a literal and mark it readonly:

-  /** @internal */
-  _buildLocation?: boolean
+  /** @internal — set only by RouterCore.buildLocation */
+  readonly _buildLocation?: true

I scanned every tsconfig*.json in the repo and didn’t find stripInternal: true, nor any api-extractor.json to filter out @internal members. Please add

{
  "compilerOptions": {
    "stripInternal": true
  }
}

to your root tsconfig.json (or configure your API‐Extractor / docs toolchain) so this flag is truly hidden in published declarations, and then verify it’s stripped as expected.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test-react-router-redirect-in-preload

🪧 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.

Copy link

nx-cloud bot commented Aug 17, 2025

View your CI Pipeline Execution ↗ for commit 8a18a9f

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded 4m 21s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1m 51s View ↗

☁️ Nx Cloud last updated this comment at 2025-08-17 12:33:21 UTC

Copy link

pkg-pr-new bot commented Aug 17, 2025

More templates

@tanstack/arktype-adapter

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

@tanstack/directive-functions-plugin

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

@tanstack/eslint-plugin-router

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

@tanstack/history

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

@tanstack/react-router

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

@tanstack/react-router-devtools

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

@tanstack/react-router-ssr-query

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

@tanstack/react-start

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

@tanstack/react-start-client

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

@tanstack/react-start-plugin

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

@tanstack/react-start-server

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

@tanstack/router-cli

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

@tanstack/router-core

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

@tanstack/router-devtools

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

@tanstack/router-devtools-core

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

@tanstack/router-generator

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

@tanstack/router-plugin

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

@tanstack/router-ssr-query-core

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

@tanstack/router-utils

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

@tanstack/router-vite-plugin

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

@tanstack/server-functions-plugin

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

@tanstack/solid-router

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

@tanstack/solid-router-devtools

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

@tanstack/solid-start

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

@tanstack/solid-start-client

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

@tanstack/solid-start-plugin

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

@tanstack/solid-start-server

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

@tanstack/start-client-core

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

@tanstack/start-plugin-core

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

@tanstack/start-server-core

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

@tanstack/start-server-functions-client

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

@tanstack/start-server-functions-fetcher

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

@tanstack/start-server-functions-server

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

@tanstack/start-storage-context

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

@tanstack/valibot-adapter

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

@tanstack/virtual-file-routes

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

@tanstack/zod-adapter

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

commit: 8a18a9f

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
packages/react-router/tests/redirect.test.tsx (3)

243-246: Replace time-based sleep with deterministic waitFor on the preload side-effect

Sleeping introduces unnecessary flakiness and test latency. Since the preload effect is observable via beforeRedirectMock, wait on that instead.

Apply this diff within the current test:

-      // preload
-      fireEvent.focus(linkToProtected)
-      await sleep(WAIT_TIME)
+      // preload
+      fireEvent.focus(linkToProtected)
+      await waitFor(() => expect(beforeRedirectMock).toHaveBeenCalledTimes(1))

And update the import at the top of the file to include waitFor (outside the changed hunk):

import {
  cleanup,
  configure,
  fireEvent,
  render,
  screen,
  waitFor,
} from '@testing-library/react'

243-249: Optionally assert no navigation happens during preload to document current semantics

If you want to explicitly document that a redirect thrown during intent-preload does not navigate (only evicts cache), you can assert location remains at “/” after the preload step. Keep in mind this is locking in current behavior; if this is intentionally unspecified, skipping is fine.

Example assertions (insert right after the preload wait):

expect(router.state.location.href).toBe('/')
expect(window.location.pathname).toBe('/')
expect(afterRedirectMock).not.toHaveBeenCalled()

257-258: Consider adding phase-specific assertions for clearer failure signals

You already assert final call counts. Adding interim checks (after preload and right after click) can make failures easier to diagnose if behavior regresses (e.g., preload called twice or navigation bypasses the guard).

For example:

  • After preload wait: expect(beforeRedirectMock).toHaveBeenCalledTimes(1)
  • Immediately after click: expect(beforeRedirectMock).toHaveBeenCalledTimes(2)
📜 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 72b65cf and 6a23244.

📒 Files selected for processing (1)
  • packages/react-router/tests/redirect.test.tsx (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/react-router/tests/redirect.test.tsx (3)
e2e/react-router/basic-file-based/src/routeTree.gen.ts (1)
  • routeTree (1041-1043)
packages/react-router/src/router.ts (1)
  • createRouter (80-82)
packages/react-router/src/RouterProvider.tsx (1)
  • RouterProvider (47-56)
⏰ 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/react-router/tests/redirect.test.tsx (1)

215-221: Good encapsulation of the preload-redirect guard; assertions are well-instrumented

Using a closure-based signedIn flag with beforeRedirectMock/afterRedirectMock cleanly captures the eviction behavior and ensures the guard re-executes on real navigation. Looks good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant