-
Notifications
You must be signed in to change notification settings - Fork 399
add signOutCallback to UserButton #7006
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?
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThis PR adds support for a customizable Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant UserButton
participant Context
participant Callback
participant Clerk
User->>UserButton: Trigger sign out
UserButton->>Context: navigateAfterSignOut called
alt signOutCallback provided
Context->>Callback: Invoke signOutCallback
Callback->>Clerk: Custom logic (e.g., redirect)
Note over Callback,Clerk: Navigation customized
else signOutCallback not provided
Context->>Clerk: redirectWithAuth (default navigation)
Note over Context,Clerk: Default navigation behavior
end
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes The changes follow a straightforward pattern: adding optional callback support with backward compatibility. Logic is localized and well-tested. The main review effort involves verifying callback integration points and ensuring the fallback behavior remains intact. Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
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 (1)
packages/clerk-js/src/ui/contexts/components/UserButton.ts (1)
34-34
: LGTM! Consider using nullish coalescing operator.The implementation correctly prioritizes
signOutCallback
over the default navigation behavior. WhensignOutCallback
is provided, it's used; otherwise, the default navigation function is created.For semantic clarity, consider using the nullish coalescing operator (
??
) instead of logical OR (||
):- const navigateAfterSignOut = signOutCallback || (() => navigate(afterSignOutUrl)); + const navigateAfterSignOut = signOutCallback ?? (() => navigate(afterSignOutUrl));
- const navigateAfterMultiSessionSingleSignOut = - signOutCallback || (() => clerk.redirectWithAuth(afterMultiSessionSingleSignOutUrl)); + const navigateAfterMultiSessionSingleSignOut = + signOutCallback ?? (() => clerk.redirectWithAuth(afterMultiSessionSingleSignOutUrl));
While both operators work identically here (since
signOutCallback
can only beundefined
or a function),??
more explicitly conveys that you're checking for null/undefined rather than general falsiness.Also applies to: 45-46
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
(3 hunks)packages/clerk-js/src/ui/contexts/components/UserButton.ts
(3 hunks)packages/types/src/clerk.ts
(3 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
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/contexts/components/UserButton.ts
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.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/contexts/components/UserButton.ts
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
packages/types/src/clerk.ts
**/*.{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/contexts/components/UserButton.ts
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
packages/types/src/clerk.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/ui/contexts/components/UserButton.ts
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
packages/types/src/clerk.ts
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/contexts/components/UserButton.ts
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
packages/types/src/clerk.ts
**/*.{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/contexts/components/UserButton.ts
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
packages/types/src/clerk.ts
**/*.{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/contexts/components/UserButton.ts
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
packages/types/src/clerk.ts
**/*.{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/__tests__/UserButton.test.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.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/__tests__/UserButton.test.tsx
**/*.test.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.test.{jsx,tsx}
: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure
Files:
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}
: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx (1)
packages/clerk-js/src/ui/components/UserButton/index.tsx (1)
UserButton
(69-69)
packages/types/src/clerk.ts (2)
packages/react/src/isomorphicClerk.ts (1)
session
(682-688)packages/types/src/session.ts (2)
SignedInSessionResource
(286-286)SessionResource
(209-262)
⏰ 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). (5)
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Build Packages
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/types/src/clerk.ts (1)
1644-1649
: LGTM!The JSDoc is clear and the type is correctly defined. The documentation accurately describes that this callback overrides the default navigation behavior.
packages/clerk-js/src/ui/components/UserButton/__tests__/UserButton.test.tsx (2)
105-127
: LGTM!The test properly verifies that:
signOutCallback
is passed toclerk.signOut
- The callback is invoked
- Navigation is bypassed when the callback is provided
This follows the existing test patterns and provides good coverage for the new feature.
205-241
: LGTM!These tests provide comprehensive coverage for multi-session scenarios:
- Signing out of all accounts with a callback
- Signing out of a single session with a callback
Both tests correctly verify that the callback is invoked and navigation is bypassed. The tests also properly check that
clerk.signOut
is called with the appropriate parameters (callback + sessionId for single session sign-out).packages/clerk-js/src/ui/contexts/components/UserButton.ts (1)
24-24
: LGTM!Correctly extracts
signOutCallback
from the context and excludes it from the spread object, as it's consumed to create the navigation functions below.
export type UnsubscribeCallback = () => void; | ||
export type BeforeEmitCallback = (session?: SignedInSessionResource | null) => void | Promise<any>; | ||
export type SetActiveNavigate = ({ session }: { session: SessionResource }) => void | Promise<unknown>; | ||
export type BeforeEmitCallback = (session?: SignedInSessionResource | null) => undefined | Promise<any>; |
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.
Use Promise<unknown>
instead of Promise<any>
for consistency.
The return type uses Promise<any>
which is less type-safe than Promise<unknown>
. Line 124 (SetActiveNavigate
) uses Promise<unknown>
, so this should follow the same pattern for consistency.
Apply this diff:
-export type BeforeEmitCallback = (session?: SignedInSessionResource | null) => undefined | Promise<any>;
+export type BeforeEmitCallback = (session?: SignedInSessionResource | null) => undefined | Promise<unknown>;
📝 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.
export type BeforeEmitCallback = (session?: SignedInSessionResource | null) => undefined | Promise<any>; | |
export type BeforeEmitCallback = (session?: SignedInSessionResource | null) => undefined | Promise<unknown>; |
🤖 Prompt for AI Agents
packages/types/src/clerk.ts around line 123: the BeforeEmitCallback type
currently returns undefined | Promise<any>; update it to use undefined |
Promise<unknown> for consistency with SetActiveNavigate and to improve type
safety — change the return type from Promise<any> to Promise<unknown> so the
type becomes (session?: SignedInSessionResource | null) => undefined |
Promise<unknown>.
export type SetActiveNavigate = ({ session }: { session: SessionResource }) => undefined | Promise<unknown>; | ||
|
||
export type SignOutCallback = () => void | Promise<any>; | ||
export type SignOutCallback = () => undefined | Promise<any>; |
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.
Use Promise<unknown>
instead of Promise<any>
for consistency.
The return type uses Promise<any>
which is less type-safe. Line 124 uses Promise<unknown>
, so this should match for consistency.
Apply this diff:
-export type SignOutCallback = () => undefined | Promise<any>;
+export type SignOutCallback = () => undefined | Promise<unknown>;
📝 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.
export type SignOutCallback = () => undefined | Promise<any>; | |
export type SignOutCallback = () => undefined | Promise<unknown>; |
🤖 Prompt for AI Agents
In packages/types/src/clerk.ts around line 126, the SignOutCallback return type
currently uses Promise<any>; change it to Promise<unknown> to match the
project's type-safety convention and be consistent with line 124. Update the
type alias so the callback returns undefined | Promise<unknown> instead of
undefined | Promise<any>.
@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: |
UserButton's
I'd strongly argue that the Something to consider is that by adding a function as a prop, the developer would need to refactor to use our component/provider inside a client component, since functions as props are not allowed in server components. |
I stumbled across this and have some questions. @jescalan What's the usecases that has come up? I can imagine things like firing off analytics events, but curious if we've heard others?
@panteliselef Aren't these statements incompatible in the case of Next? The provider is and needs to be a server component, so we can't pass in a function there? I might be misunderstanding or missing something which is why I wanted to ask. |
Description
Clerk's
signOut
method offers asignOutCallback
param which can be used for redirects, but can also be used for anything else a developer needs to do or clean up when signing a user out, such as cleaning up local storage, running analytics events, etc.Previously, we had a prop on
UserButton
that allowed passing in a custom function in this way, but it was removed in Core 2 under the premise that it was only really used for redirecting after sign out and providing an after sign out URL prop would add simplicity and consistency with other component APIs.I think this was a poorly considered change, as there are a variety of other things that developers could want to do on sign out and this is no longer possible unless you build your own
UserButton
component. We have received customer feedback confirming this need.This PR re-introduces the
signOutCallback
parameter toUserButton
, but without changing anything else. If bothsignOutCallback
andafterSignOutUrl
are passed,signOutCallback
will override theafterSignOutUrl
redirect behavior.Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
signOutCallback
prop to customize post-sign-out behavior, allowing developers to override default navigation with custom handlers for both single and multi-session scenarios.