-
-
Notifications
You must be signed in to change notification settings - Fork 131
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
base: main
Are you sure you want to change the base?
feat(cli): TanStack Router beforeLoad auth checks #439
Conversation
…_root.tsx.hbs Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
🦋 Changeset detectedLatest commit: 8bcf302 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
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 |
WalkthroughThe 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
Sequence Diagram(s)Authentication Flow with Dynamic RedirectsequenceDiagram
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
Login Route Pre-Load RedirectsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
✨ Finishing Touches🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 parametersThe
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
📒 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 correctThe 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 implementationThe
beforeLoad
hook correctly implements authentication checks and redirects unauthenticated users while preserving their intended destination.
9-9
: Use router-suppliedlocation
in route hooksDirectly referencing
window.location
breaks SSR and certain test setups. TanStack Router’s hooks (e.g.beforeLoad
/loader
/action
) receive alocation
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 protectionMoving 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'sbeforeLoad
hook.apps/cli/templates/auth/web/react/tanstack-router/src/components/sign-up-form.tsx (1)
3-3
: LGTM: Import addition is correctThe 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 contextThe 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 IntegrationThe 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 theconvex/react
hooks, with no need for auser
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 andzod
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
: Ensureuser
is provided in your Router contextYour
beforeLoad
hook correctly guards against logged-in users accessing the login route. To make surecontext.user
is actually defined at runtime, verify your router setup (e.g. in yoursrc/index.tsx
or entry file) includes acontext
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 insidebeforeLoad
. Please confirm that your entry point includes acontext
withuser
.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
navigate({ | ||
to: "/dashboard", | ||
to: search.redirect, | ||
}); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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" }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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
Refactor