-
Notifications
You must be signed in to change notification settings - Fork 377
fix(clerk-js): Improve multi-session navigation to tasks #6575
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
fix(clerk-js): Improve multi-session navigation to tasks #6575
Conversation
The latest updates on your projects. Learn more about Vercel for GitHub.
|
🦋 Changeset detectedLatest commit: 0d4d009 The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
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 |
@@ -125,6 +126,4 @@ const SignInAccountSwitcherInternal = () => { | |||
</Flow.Part> | |||
); | |||
}; | |||
export const SignInAccountSwitcher = withRedirectToSignInTask( |
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.
I've removed the withRedirectToSignInTask
guard from here since the user should be allowed to switch sessions regardless if they have a pending task
b504670
to
0d4d009
Compare
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
📝 WalkthroughWalkthrough
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type 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: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
.changeset/sour-meals-see.md (1)
6-6
: Stray character will break changeset parsingThere’s a lone “6” on Line 6. Changesets expect frontmatter and the message only; this extra character will cause parsing failures in the release pipeline.
Apply this diff to fix:
Improve multi-session navigation to tasks -6 +packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx (1)
79-89
: Prioritize taskUrl before afterSwitchSessionUrl to meet the path-routing intentAs written, if the target session has no currentTask and afterSwitchSessionUrl is set, we navigate there before considering taskUrl. This can bypass the intended tasks route (e.g., /sign-in/tasks/choose-organization) and regress the fix goal. Task-based navigation should take precedence whenever taskUrl is provided by the SignIn flow.
Apply this reordering:
navigate: async ({ session }) => { - if (!session.currentTask && opts.afterSwitchSessionUrl) { - await navigate(opts.afterSwitchSessionUrl); - return; - } - - if (opts.taskUrl) { + if (opts.taskUrl) { await navigate(opts.taskUrl); return; } + if (!session.currentTask && opts.afterSwitchSessionUrl) { + await navigate(opts.afterSwitchSessionUrl); + return; + } await navigateIfTaskExists(session, { baseUrl: opts.signInUrl ?? displayConfig.signInUrl, navigate, });
♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx (1)
129-129
: Removal of withRedirectToSignInTask guard is appropriate hereAligns with the intent to allow session switching even if there are pending tasks; redirection is now handled post-selection via taskUrl in the hook.
🧹 Nitpick comments (3)
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx (3)
21-22
: Document the new public param and align nullabilityThe new param extends a public type. Add JSDoc so downstream users understand precedence and intent. Also consider simplifying to
taskUrl?: string
(omit null) unless null carries distinct semantics elsewhere.Suggested JSDoc (place above the type or the property):
/** * When provided, navigation after switching sessions will go to this URL immediately, * bypassing per-session task checks and the `afterSwitchSessionUrl`. * Intended for path-based SignIn flows (e.g., /sign-in/tasks/choose-organization). */ taskUrl?: string | null;
24-24
: Consider explicit return type for the exported hookPer project guidelines, public APIs should have explicit return types. Defining and exporting a
UseMultisessionActionsReturn
interface improves stability for consumers and avoids accidental breaking changes.Example:
// Define once near the hook export interface UseMultisessionActionsReturn { handleSignOutSessionClicked: (session: SignedInSessionResource) => () => Promise<unknown> | void; handleManageAccountClicked: () => Promise<unknown> | void; handleUserProfileActionClicked: (__experimental_startPath?: string) => Promise<unknown> | void; handleSignOutAllClicked: () => Promise<unknown> | void; handleSessionClicked: (session: SignedInSessionResource) => () => Promise<void>; handleAddAccountClicked: () => Promise<void>; otherSessions: readonly SignedInSessionResource[]; signedInSessions: readonly SignedInSessionResource[]; } // Then annotate: export const useMultisessionActions = (opts: UseMultisessionActionsParams): UseMultisessionActionsReturn => { // ... };
74-99
: Add tests for new navigation precedenceNo tests were added. Please add tests covering:
- When taskUrl is provided: navigation goes to taskUrl regardless of target session’s currentTask or afterSwitchSessionUrl.
- When taskUrl is absent and target session has no currentTask: navigation goes to afterSwitchSessionUrl.
- When taskUrl is absent and target session has a currentTask: falls back to navigateIfTaskExists.
These should mock setActive, navigate, and navigateIfTaskExists to assert call order.
I can scaffold a Jest test with minimal mocks for useRouter.navigate, setActive, and navigateIfTaskExists if helpful.
📜 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
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
.changeset/sour-meals-see.md
(1 hunks)packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
(3 hunks)packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
packages/clerk-js/src/ui/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/clerk-js-ui.mdc)
packages/clerk-js/src/ui/**/*.{ts,tsx}
: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}
: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
**/*.{ts,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}
: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertions
for literal types:as const
Usesatisfies
operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
**/*.{jsx,tsx}
📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}
: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}
: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile
,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
**/*.tsx
📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)
**/*.tsx
: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
**/*
⚙️ CodeRabbit Configuration File
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
Files:
packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx
.changeset/**
📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/sour-meals-see.md
🧬 Code Graph Analysis (1)
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx (4)
packages/clerk-js/src/ui/contexts/components/SignIn.ts (1)
useSignInContext
(38-169)packages/clerk-js/src/ui/components/UserButton/useMultisessionActions.tsx (1)
useMultisessionActions
(24-116)packages/clerk-js/src/ui/common/withRedirect.tsx (1)
withRedirectToAfterSignIn
(55-72)packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
withCardStateProvider
(72-81)
⏰ 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). (6)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (generic, chrome)
🔇 Additional comments (4)
.changeset/sour-meals-see.md (1)
1-5
: Changeset entry looks goodPatch release and description accurately reflect the change scope.
packages/clerk-js/src/ui/components/SignIn/SignInAccountSwitcher.tsx (3)
8-8
: Import update looks correctSwitching to only withRedirectToAfterSignIn matches the stated behavior change and simplifies the wrapper chain.
18-18
: Correctly wiring taskUrl from SignIn contextIncluding taskUrl from useSignInContext is necessary for path-based task navigation. Ensure the context guarantees taskUrl when the SignIn flow requires tasks; otherwise it should be null/undefined.
Would you like me to scan for other SignIn consumers that may also need to pass taskUrl into multisession flows?
22-28
: Passing taskUrl to multisession actions is the right integration pointThis keeps the SignIn-specific path-routing logic encapsulated in the hook without leaking it into the UI layer. Once the hook prioritizes taskUrl (see earlier comment), this will fulfill the PR objective.
Description
With improvements
Uses path routing from
SignInContext.taskUrl
to perform navigation from/sign-in/choose
to/sign-in/tasks/choose-organization
CleanShot.2025-08-19.at.17.14.07.mp4
🐛
CleanShot.2025-08-19.at.17.18.54.mp4
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Chores