Skip to content

feat(cli): TanStack Router beforeLoad auth checks #439

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 6 commits into
base: main
Choose a base branch
from

Conversation

BrennenRocks
Copy link

@BrennenRocks BrennenRocks commented Jul 31, 2025

Here are the docs from TanStack Router about Authenticated Routes: https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes

This change creates an _auth.tsx which handles redirects if someone tries to access authenticated pages when they're not logged in. It also creates an _auth directory in the routes folder to put all of your authenticated pages.

I also added a redirect to the login pages to make sure someone will be correctly redirected to the page they were trying to access before they were brought to the login page

Summary by CodeRabbit

  • New Features

    • Improved post-login and post-sign-up navigation to dynamically redirect users based on URL parameters.
    • Added route protection with automatic redirection for unauthenticated users attempting to access protected routes.
    • Enhanced login route to validate redirect parameters and prevent authenticated users from accessing the login page.
    • Integrated user session retrieval and context propagation throughout the app for authenticated experiences.
  • Refactor

    • Updated route paths and structure to better support authentication workflows and protected routes.
    • Modified router context initialization to conditionally include user information when authentication is enabled.

Copy link

changeset-bot bot commented Jul 31, 2025

🦋 Changeset detected

Latest commit: 8bcf302

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
create-better-t-stack Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

Copy link
Contributor

coderabbitai bot commented Jul 31, 2025

Walkthrough

The changes implement dynamic authentication-aware routing in a React TanStack Router template. They introduce user context to the router, enforce route protection and redirects based on authentication state, and enable flexible post-auth navigation using query parameters. The modifications span route definitions, context initialization, and authentication forms.

Changes

Cohort / File(s) Change Summary
Sign-In & Sign-Up Forms
apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-in-form.tsx, apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-up-form.tsx
Integrated useSearch from TanStack Router to dynamically determine post-authentication redirect targets based on query parameters, replacing hardcoded navigation paths.
Authentication Route Protection
apps/cli/templates/auth/web/react/tanstack-router/src/routes/_auth.tsx
Added a protected route at /_auth with a beforeLoad hook to redirect unauthenticated users to /login, preserving the intended destination via a redirect query parameter.
Dashboard Route Update
apps/cli/templates/auth/web/react/tanstack-router/src/routes/_auth/dashboard.tsx.hbs
Changed route path from /dashboard to /_auth/dashboard and removed manual session checks and redirects, relying on parent route protection.
Login Route Enhancements
apps/cli/templates/auth/web/react/tanstack-router/src/routes/login.tsx
Added search parameter validation for redirect using zod and a beforeLoad hook to redirect authenticated users away from the login page to their intended destination.
Router Context Initialization
apps/cli/templates/frontend/react/tanstack-router/src/main.tsx.hbs
Modified router context initialization to conditionally include user: null when authentication is enabled, ensuring user context is available throughout the app.
Root Route Authentication Context
apps/cli/templates/frontend/react/tanstack-router/src/routes/__root.tsx.hbs
Added user session retrieval in a beforeLoad hook, extending the router context to include a user property, and making user state available to all descendant routes.
Changelog Entry
.changeset/salty-windows-crash.md
Added a changeset documenting the authentication checks performed in TanStack Router’s beforeLoad lifecycle, serving as a descriptive patch note without code changes.

Sequence Diagram(s)

Authentication Flow with Dynamic Redirect

sequenceDiagram
    participant User
    participant SignInForm
    participant Router
    participant AuthAPI
    participant RootRoute
    participant _authRoute

    User->>SignInForm: Submit credentials
    SignInForm->>AuthAPI: Authenticate user
    AuthAPI-->>SignInForm: Success
    SignInForm->>Router: Navigate to search.redirect (from query)
    Router->>RootRoute: beforeLoad (fetch user session)
    RootRoute-->>Router: { user }
    Router->>_authRoute: beforeLoad (check user)
    alt user exists
        _authRoute-->>Router: Allow access
    else user missing
        _authRoute-->>Router: Redirect to /login?redirect=originalPath
    end
Loading

Login Route Pre-Load Redirect

sequenceDiagram
    participant User
    participant LoginRoute
    participant RootRoute
    participant AuthAPI

    User->>LoginRoute: Access /login?redirect=/foo
    LoginRoute->>RootRoute: beforeLoad (fetch user session)
    RootRoute-->>LoginRoute: { user }
    alt user exists
        LoginRoute-->>User: Redirect to /foo
    else user missing
        LoginRoute-->>User: Show login form
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A bunny hops through routes anew,
With auth-aware redirects in view.
Context set and users checked,
No stray guests can now defect!
Dynamic paths, a seamless dance—
Secure and nimble, apps advance.
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 bffc6be and 8bcf302.

📒 Files selected for processing (1)
  • .changeset/salty-windows-crash.md (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .changeset/salty-windows-crash.md
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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
Contributor

@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: 2

🧹 Nitpick comments (4)
apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-in-form.tsx (1)

16-16: Consider adding fallback for search parameters

The useSearch call assumes the /login route exists and provides search parameters. Consider adding error handling or a fallback mechanism if the search parameters are unavailable.

- const search = useSearch({ from: "/login" });
+ const search = useSearch({ from: "/login" }) || { redirect: "/dashboard" };
apps/cli/templates/auth/web/react/tanstack-router/src/routes/login.tsx (1)

7-7: Consider making the fallback redirect configurable.

The hardcoded fallback redirect to "/dashboard" works for the current implementation, but consider making this configurable through environment variables or a configuration file for better flexibility across different deployment environments.

-const fallbackRedirect = "/dashboard";
+const fallbackRedirect = process.env.VITE_DEFAULT_REDIRECT || "/dashboard";
apps/cli/templates/frontend/react/tanstack-router/src/routes/__root.tsx.hbs (2)

58-68: Robust session fetching with proper error handling.

The beforeLoad hook implementation is well-structured:

  • Proper async/await usage
  • Comprehensive error handling with try-catch
  • Graceful fallback to null user on failure
  • Appropriate error logging

However, consider the security implications of error logging in production.

Consider sanitizing error logs in production to avoid exposing sensitive information:

    } catch (error) {
-      console.error('Failed to fetch user session:', error);
+      console.error('Failed to fetch user session:', process.env.NODE_ENV === 'development' ? error : 'Session fetch failed');
      return { user: null };
    }

94-94: Minor formatting inconsistency.

There's an extra blank line added here that seems unintentional and doesn't align with the existing code formatting.

-  {{#if (eq api "orpc")}}
-
+  {{#if (eq api "orpc")}}
   const [client] = useState<RouterClient<typeof appRouter>>(() => createORPCClient(link));
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between dc6f6eb and bffc6be.

📒 Files selected for processing (7)
  • apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-in-form.tsx (3 hunks)
  • apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-up-form.tsx (3 hunks)
  • apps/cli/templates/auth/web/react/tanstack-router/src/routes/_auth.tsx (1 hunks)
  • apps/cli/templates/auth/web/react/tanstack-router/src/routes/_auth/dashboard.tsx.hbs (1 hunks)
  • apps/cli/templates/auth/web/react/tanstack-router/src/routes/login.tsx (1 hunks)
  • apps/cli/templates/frontend/react/tanstack-router/src/main.tsx.hbs (3 hunks)
  • apps/cli/templates/frontend/react/tanstack-router/src/routes/__root.tsx.hbs (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/cli/templates/auth/web/react/tanstack-router/src/routes/login.tsx (1)
apps/cli/templates/auth/web/react/react-router/src/components/sign-up-form.tsx (1)
  • SignUpForm (11-160)
🔇 Additional comments (12)
apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-in-form.tsx (1)

3-3: LGTM: Import addition is correct

The addition of useSearch to the imports is appropriate for accessing search parameters.

apps/cli/templates/auth/web/react/tanstack-router/src/routes/_auth.tsx (2)

3-15: Excellent route protection implementation

The beforeLoad hook correctly implements authentication checks and redirects unauthenticated users while preserving their intended destination.


9-9: Use router-supplied location in route hooks

Directly referencing window.location breaks SSR and certain test setups. TanStack Router’s hooks (e.g. beforeLoad/loader/action) receive a location object—use that instead:

• File: apps/cli/templates/auth/web/react/tanstack-router/src/routes/_auth.tsx, around Line 9

- beforeLoad: ({ params, context }) => {
-   return { redirect: `${location.pathname}${location.search}${location.hash}` };
- },
+ beforeLoad: ({ location, params, context }) => {
+   return { redirect: `${location.pathname}${location.search}${location.hash}` };
+ },

Please verify that your hook signature indeed provides a location parameter before applying this change.

apps/cli/templates/auth/web/react/tanstack-router/src/routes/_auth/dashboard.tsx.hbs (1)

13-15: Excellent refactoring to use centralized route protection

Moving the dashboard under the /_auth route and removing manual redirect logic is a clean improvement. The authentication check is now handled by the parent route's beforeLoad hook.

apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-up-form.tsx (1)

3-3: LGTM: Import addition is correct

The addition of useSearch to the imports is appropriate for accessing search parameters.

apps/cli/templates/frontend/react/tanstack-router/src/main.tsx.hbs (2)

24-24: Correct implementation of conditional user context

The conditional addition of user: null to the router context when authentication is enabled is implemented correctly across different API configurations.

Also applies to: 33-33, 47-49


42-42: Confirm Convex Authentication Integration

The Convex branch of the router is currently using:

context: {},
Wrap: ({ children }) => <ConvexProvider client={convex}>{children}</ConvexProvider>

– it never injects a user property even when --auth is enabled. Please verify whether:

  • Authentication is intended to be handled exclusively via the ConvexProvider and the convex/react hooks, with no need for a user field in the TanStack router context;
  • Or, if you do need to access user in route loaders you should update this section to include it, for example:
    {{#if (eq backend "convex")}}
    - context: {},
    + context: { user: null },
      Wrap: function WrapComponent({ children }: { children: React.ReactNode }) {
        return <ConvexProvider client={convex}>{children}</ConvexProvider>;
      },
    {{/if}}

Let me know which approach is correct.

apps/cli/templates/auth/web/react/tanstack-router/src/routes/login.tsx (3)

3-5: LGTM! Proper imports for authentication flow.

The imports are correctly structured for the authentication-aware routing implementation. The redirect function from TanStack Router and zod for validation are essential for the new functionality.


10-12: Excellent search parameter validation.

The zod schema properly validates and defaults the redirect parameter, ensuring type safety and providing a sensible fallback. This aligns well with TanStack Router's validation patterns.


13-17: Ensure user is provided in your Router context

Your beforeLoad hook correctly guards against logged-in users accessing the login route. To make sure context.user is actually defined at runtime, verify your router setup (e.g. in your src/index.tsx or entry file) includes a context prop on <RouterProvider>:

import { createReactRouter, RouterProvider } from '@tanstack/react-router'
// … your route definitions …
const router = createReactRouter({ /* routes */ })
const currentUser = await fetchCurrentUser()

ReactDOM.createRoot(document.getElementById('root')!).render(
  <RouterProvider
    router={router}
    context={{ user: currentUser }}
  />
)

This ensures context.user is available inside beforeLoad. Please confirm that your entry point includes a context with user.

apps/cli/templates/frontend/react/tanstack-router/src/routes/__root.tsx.hbs (2)

20-23: LGTM! Proper conditional imports for authentication.

The conditional imports using Handlebars syntax correctly include the necessary authentication dependencies only when the auth flag is enabled, keeping the bundle size optimized for non-auth scenarios.


37-39: Consistent user context interface extension.

The user: User | null property is consistently added across all RouterAppContext interface variants (orpc, trpc, and default). This ensures type safety and proper context typing throughout the application.

Also applies to: 45-47, 51-53

Comment on lines 35 to 37
navigate({
to: "/dashboard",
to: search.redirect,
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Validate redirect URL to prevent open redirects

Using search.redirect directly for navigation creates a security vulnerability. Malicious actors could craft URLs with arbitrary redirect destinations, leading to open redirect attacks.

Add validation to ensure the redirect URL is safe:

  onSuccess: () => {
+   const safeRedirect = search.redirect?.startsWith('/') ? search.redirect : '/dashboard';
    navigate({
-     to: search.redirect,
+     to: safeRedirect,
    });
    toast.success("Sign in successful");
  },
📝 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.

Suggested change
navigate({
to: "/dashboard",
to: search.redirect,
});
onSuccess: () => {
const safeRedirect = search.redirect?.startsWith('/') ? search.redirect : '/dashboard';
navigate({
to: safeRedirect,
});
toast.success("Sign in successful");
},
🤖 Prompt for AI Agents
In
apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-in-form.tsx
around lines 35 to 37, the code uses search.redirect directly for navigation,
which can cause open redirect vulnerabilities. To fix this, add validation to
check that the redirect URL is safe and allowed before calling navigate.
Implement a whitelist or ensure the redirect URL is relative and does not lead
to external sites, and only navigate if the URL passes this validation.

@@ -13,6 +13,7 @@ export default function SignUpForm({
}: {
onSwitchToSignIn: () => void;
}) {
const search = useSearch({ from: "/login" });
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Same security concern as sign-in form

This component has the same open redirect vulnerability as the sign-in form. The search.redirect value should be validated before navigation.

Apply the same validation as suggested for the sign-in form:

  const search = useSearch({ from: "/login" });
  
  // ... later in onSuccess
  onSuccess: () => {
+   const safeRedirect = search.redirect?.startsWith('/') ? search.redirect : '/dashboard';
    navigate({
-     to: search.redirect,
+     to: safeRedirect,
    });
    toast.success("Sign up successful");
  },

Also applies to: 37-39

🤖 Prompt for AI Agents
In
apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-up-form.tsx
at lines 16 and 37-39, the use of search.redirect for navigation introduces an
open redirect vulnerability. To fix this, validate the search.redirect value
against a whitelist of allowed paths or ensure it is a relative path within the
application before using it for navigation. Implement the same validation logic
as applied in the sign-in form to prevent unsafe redirects.

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

Successfully merging this pull request may close these issues.

1 participant