-
Notifications
You must be signed in to change notification settings - Fork 382
chore(shared,clerk-react): Support useCheckout while clerk-js still loads #6720
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?
chore(shared,clerk-react): Support useCheckout while clerk-js still loads #6720
Conversation
…mentelement-to-not-require
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThe checkout flow was refactored across UI, React, and shared layers: UI gating switched from id-based checks to plan/status/totals; React’s isomorphic entry now conditionally delegates checkout to ClerkJS or a StateProxy fallback; StateProxy adds a concrete checkoutSignal API; useCheckout now uses context, updated error timing, and streamlined subscriptions. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor App
participant IsomorphicClerk
participant ClerkJS as ClerkJS (__experimental_checkout)
participant StateProxy
App->>IsomorphicClerk: __experimental_checkout(params)
alt ClerkJS loaded
IsomorphicClerk->>ClerkJS: __experimental_checkout(params)
ClerkJS-->>App: CheckoutInstance
else Not loaded / SSR
IsomorphicClerk->>StateProxy: checkoutSignal(params)
StateProxy-->>App: CheckoutInstance (proxy)
end
sequenceDiagram
autonumber
actor Component
participant StateProxy
participant Clerk as Clerk (__experimental_checkout)
note over StateProxy: buildCheckoutProxy(params)
Component->>StateProxy: checkoutSignal(params)
StateProxy-->>Component: Proxy with methods
rect rgb(235, 245, 255)
note right of Component: Using proxy methods
Component->>StateProxy: start()/confirm()/clear()
StateProxy->>Clerk: gate + invoke when browser & loaded
Clerk-->>StateProxy: result
StateProxy-->>Component: result/Promise
end
rect rgb(255, 240, 240)
note over StateProxy,Component: Server call
Component->>StateProxy: finalize() (server)
StateProxy-->>Component: throw server-not-supported
end
Component->>StateProxy: subscribe(listener)
StateProxy-->>Component: unsubscribe fn
sequenceDiagram
autonumber
actor UI as CheckoutForm
participant Hook as useCheckout
participant Ctx as ClerkInstanceContext
participant Manager
UI->>Hook: useCheckout({ for, planId, planPeriod })
Hook->>Ctx: useClerkInstanceContext()
Ctx-->>Hook: clerk instance
Hook->>Manager: create/memoize manager
Hook->>Hook: useSyncExternalStore( subscribe, getState )
alt isLoaded && no user / invalid org
Hook-->>UI: throw error
else
Hook-->>UI: { state, actions }
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
✨ Finishing Touches
🧪 Generate unit tests
🪧 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
Status, Documentation and Community
|
@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: |
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: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (3)
29-35
: Prevent crash when totals are not ready
totals
is used extensively below; guarding only onplan
risks runtime errors during initialization.Apply:
- const { plan, totals, isImmediatePlanChange, planPeriod, freeTrialEndsAt } = checkout; - - if (!plan) { + const { plan, totals, isImmediatePlanChange, planPeriod, freeTrialEndsAt } = checkout; + if (!plan || !totals) { return null; }
209-213
: Localize aria-labelPer UI guidelines, no hard-coded user-facing strings. Replace with a localization key.
Apply:
- <SegmentedControl.Root - aria-label='Payment method source' + <SegmentedControl.Root + aria-label={localizationKeys('commerce.checkout.paymentMethodSourceAriaLabel')}If a key does not exist, add one in the localization bundle.
165-171
: Validatepayment_source_id
before confirmingDefensive check prevents passing an empty/invalid ID to
confirm
.Apply:
- const paymentSourceId = data.get('payment_source_id') as string; - - return confirmCheckout({ - paymentSourceId, - }); + const paymentSourceId = String(data.get('payment_source_id') ?? ''); + if (!paymentSourceId) { + card.setError(localizationKeys('commerce.errors.missingPaymentSource')); + return; + } + return confirmCheckout({ paymentSourceId });packages/shared/src/react/hooks/useCheckout.ts (1)
152-158
: Avoid unbound method references in returned APIRe-exposing manager methods by reference can drop their this context. Wrap them to preserve binding.
const checkout = { ...properties, - getState: manager.getState, - start: manager.start, - confirm: manager.confirm, - clear: manager.clear, - finalize: manager.finalize, + getState: () => manager.getState(), + start: (...args: Parameters<typeof manager.start>) => manager.start(...args), + confirm: (...args: Parameters<typeof manager.confirm>) => manager.confirm(...args), + clear: () => manager.clear(), + finalize: (params?: { navigate?: SetActiveNavigate }) => manager.finalize(params),
🧹 Nitpick comments (8)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (3)
197-200
: Avoid early return churn: colocate gating with parent or memoizeThis secondary
!totals
guard is redundant once the top-level guard is in place. Remove it to simplify.Apply:
- if (!totals) { - return null; - } + // totals guaranteed by parent guard
141-146
: Make the error actionable and informativeThrowing
'Checkout not found'
hides the actual state. Include the current status to aid debugging, or handle it gracefully.Apply:
- if (status !== 'needs_confirmation') { - throw new Error('Checkout not found'); - } + if (status !== 'needs_confirmation') { + throw new Error(`Clerk: Cannot confirm checkout in status "${status}". Expected "needs_confirmation".`); + }Alternatively, surface a localized UI error instead of throwing.
368-371
: VerifyshouldDefaultBeUsed
semantics (name vs. behavior)When
shouldDefaultBeUsed
is true, the Select is shown (i.e., not using default automatically). Either invert the condition or rename for clarity.Example rename:
- const shouldDefaultBeUsed = totalDueNow.amount === 0 || !freeTrialEndsAt; + const shouldShowSelector = totalDueNow.amount === 0 || !freeTrialEndsAt; ... - {shouldDefaultBeUsed ? ( + {shouldShowSelector ? (Please confirm intended UX.
packages/react/src/stateProxy.ts (3)
50-53
: Public API should have explicit return typeAdd an explicit return type to
checkoutSignal
per package TS guidelines.Apply:
- checkoutSignal(params: CheckoutSignalProps) { + checkoutSignal(params: CheckoutSignalProps): __experimental_CheckoutInstance { return this.buildCheckoutProxy(params); }
174-195
: getState defaults look good; consider freezing to signal immutabilityOptional: freeze the default state object to avoid accidental mutation when used before load.
Example:
- getState: gateSyncMethod(target, 'getState', { + getState: gateSyncMethod(target, 'getState', Object.freeze({ isStarting: false, isConfirming: false, error: null, checkout: null, fetchStatus: 'idle', status: 'needs_initialization', - }), + }) as const),
122-173
: Remove large commented-out proxyDead/commented code adds noise and risks divergence.
Please delete the commented
buildCheckoutProxy
implementation to keep the file focused.packages/shared/src/react/hooks/useCheckout.ts (2)
67-78
: Remove commented-out V2 type blockDead/commented code adds noise and can confuse API consumers scanning the source. Delete this block or move the proposal to a tracking issue.
-// type __experimental_UseCheckoutReturnV2 = FetchStatusAndError & { -// checkout: CheckoutPropertiesPerStatus & { -// confirm: __experimental_CheckoutInstance['confirm']; -// start: __experimental_CheckoutInstance['start']; -// clear: () => void; -// finalize: (params?: { navigate?: SetActiveNavigate }) => void; -// getState: () => __experimental_CheckoutCacheState; -// isStarting: boolean; -// isConfirming: boolean; -// }; -// };
81-81
: Add JSDoc for the public hookPublic APIs require JSDoc per guidelines. Briefly document params, return, and usage outside/inside .
/** * useCheckout * Returns a live checkout controller and state for Clerk Commerce. * * Usage: * - Inside <Checkout />: options are sourced from context. * - Outside <Checkout />: pass { for, planId, planPeriod }. * * @public * @param options - Optional configuration ({ for: 'user' | 'organization'; planId?: string; planPeriod?: 'month' | 'year'; }) * @returns __experimental_UseCheckoutReturn */
📜 Review details
Configuration used: Path: .coderabbit.yaml
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.
📒 Files selected for processing (4)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
(3 hunks)packages/react/src/isomorphicClerk.ts
(1 hunks)packages/react/src/stateProxy.ts
(6 hunks)packages/shared/src/react/hooks/useCheckout.ts
(2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/react/src/isomorphicClerk.ts
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/react/src/stateProxy.ts
packages/shared/src/react/hooks/useCheckout.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/react/src/isomorphicClerk.ts
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/react/src/stateProxy.ts
packages/shared/src/react/hooks/useCheckout.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/react/src/stateProxy.ts
packages/shared/src/react/hooks/useCheckout.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/react/src/isomorphicClerk.ts
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/react/src/stateProxy.ts
packages/shared/src/react/hooks/useCheckout.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/react/src/isomorphicClerk.ts
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/react/src/stateProxy.ts
packages/shared/src/react/hooks/useCheckout.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/react/src/isomorphicClerk.ts
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/react/src/stateProxy.ts
packages/shared/src/react/hooks/useCheckout.ts
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/Checkout/CheckoutForm.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/Checkout/CheckoutForm.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/Checkout/CheckoutForm.tsx
🧬 Code graph analysis (3)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4)
packages/react/src/stateProxy.ts (1)
checkout
(210-214)packages/clerk-js/src/ui/elements/contexts/index.tsx (1)
useCardState
(42-70)packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
usePaymentMethods
(32-40)packages/shared/src/react/hooks/usePaymentMethods.tsx (1)
usePaymentMethods
(9-21)
packages/react/src/stateProxy.ts (3)
packages/types/src/commerce.ts (2)
ForPayerType
(134-134)CommerceSubscriptionPlanPeriod
(151-151)packages/types/src/clerk.ts (2)
__experimental_CheckoutInstance
(91-98)Clerk
(164-887)packages/clerk-js/src/utils/runtime.ts (1)
inBrowser
(1-3)
packages/shared/src/react/hooks/useCheckout.ts (2)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
useCheckoutContext
(10-37)packages/react/src/isomorphicClerk.ts (2)
user
(684-690)organization
(692-698)
⏰ 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: Build Packages
- GitHub Check: semgrep/ci
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/react/src/stateProxy.ts (1)
210-214
: Double-check for recursion risks
checkout
getter delegates toisomorphicClerk.__experimental_checkout
. SincebuildCheckoutProxy
waits for load before invoking, recursion is avoided. Please confirm this invariant remains true if future changes alter load gating.packages/shared/src/react/hooks/useCheckout.ts (3)
11-11
: Good switch to context-based Clerk instance retrievalUsing useClerkInstanceContext reduces coupling to the React package and plays nicer with isomorphic usage.
88-91
: Better error timingThrowing only when isLoaded and no user avoids premature errors during hydration/SSR.
92-96
: Org-guard after load is correctValidating forOrganization === 'organization' only after load prevents false positives. Message is actionable.
const { checkout } = useCheckout(); | ||
const { id, totals, freeTrialEndsAt } = checkout; | ||
const { totals, freeTrialEndsAt } = checkout; | ||
const { data: paymentSources } = usePaymentMethods(); | ||
|
||
const [paymentMethodSource, setPaymentMethodSource] = useState<PaymentMethodSource>(() => | ||
paymentSources.length > 0 ? 'existing' : 'new', | ||
); | ||
|
||
if (!id) { | ||
if (!totals) { |
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.
🛠️ Refactor suggestion
Default paymentSources
to an empty array
usePaymentMethods()
can return undefined
before data arrives; direct .length
access can throw.
Apply:
- const { data: paymentSources } = usePaymentMethods();
+ const { data: paymentSourcesRaw } = usePaymentMethods();
+ const paymentSources = paymentSourcesRaw ?? [];
📝 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.
const { checkout } = useCheckout(); | |
const { id, totals, freeTrialEndsAt } = checkout; | |
const { totals, freeTrialEndsAt } = checkout; | |
const { data: paymentSources } = usePaymentMethods(); | |
const [paymentMethodSource, setPaymentMethodSource] = useState<PaymentMethodSource>(() => | |
paymentSources.length > 0 ? 'existing' : 'new', | |
); | |
if (!id) { | |
if (!totals) { | |
const { checkout } = useCheckout(); | |
const { totals, freeTrialEndsAt } = checkout; | |
const { data: paymentSourcesRaw } = usePaymentMethods(); | |
const paymentSources = paymentSourcesRaw ?? []; | |
const [paymentMethodSource, setPaymentMethodSource] = useState<PaymentMethodSource>(() => | |
paymentSources.length > 0 ? 'existing' : 'new', | |
); | |
if (!totals) { |
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx around lines
189 to 197, usePaymentMethods() can return undefined and accessing .length may
throw; default the destructured paymentSources to an empty array (e.g., const {
data: paymentSources = [] } = usePaymentMethods()) and keep the useState
initializer relying on paymentSources.length to choose 'existing' or 'new'.
__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => { | ||
return this.clerkjs?.__experimental_checkout(...args); | ||
return this.loaded && this.clerkjs | ||
? this.clerkjs.__experimental_checkout(...args) | ||
: this.#stateProxy.checkoutSignal(...args); | ||
}; |
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.
🛠️ Refactor suggestion
Harden fallback and add explicit return type for __experimental_checkout
- Guard for older ClerkJS versions where
__experimental_checkout
may be missing even when loaded. - Add an explicit return type to satisfy our TS public-API guideline.
Apply:
- __experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => {
- return this.loaded && this.clerkjs
- ? this.clerkjs.__experimental_checkout(...args)
- : this.#stateProxy.checkoutSignal(...args);
- };
+ __experimental_checkout: Clerk['__experimental_checkout'] = (...args) => {
+ return this.loaded && this.clerkjs?.__experimental_checkout
+ ? this.clerkjs.__experimental_checkout(...args)
+ : this.#stateProxy.checkoutSignal(...args);
+ };
📝 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.
__experimental_checkout = (...args: Parameters<Clerk['__experimental_checkout']>) => { | |
return this.clerkjs?.__experimental_checkout(...args); | |
return this.loaded && this.clerkjs | |
? this.clerkjs.__experimental_checkout(...args) | |
: this.#stateProxy.checkoutSignal(...args); | |
}; | |
__experimental_checkout: Clerk['__experimental_checkout'] = (...args) => { | |
return this.loaded && this.clerkjs?.__experimental_checkout | |
? this.clerkjs.__experimental_checkout(...args) | |
: this.#stateProxy.checkoutSignal(...args); | |
}; |
🤖 Prompt for AI Agents
In packages/react/src/isomorphicClerk.ts around lines 737 to 741, the
__experimental_checkout implementation assumes clerkjs exposes that method when
loaded and lacks an explicit return type; update it to have an explicit return
type (matching Clerk['__experimental_checkout'] or its resolved return type) and
harden the runtime guard by checking that this.loaded && this.clerkjs && typeof
this.clerkjs.__experimental_checkout === 'function' before calling it, otherwise
call and return this.#stateProxy.checkoutSignal(...args); ensure the signature
and return type align with the public API guideline.
private gateListenerMethod<T extends object, K extends keyof T>( | ||
getTarget: () => T, | ||
key: T[K] extends (...args: any[]) => void ? K : never, | ||
): T[K] { | ||
// This method should only be used with keys that point to void-returning functions | ||
type F = Extract<T[K], (...args: any[]) => void>; | ||
return ((...args: Parameters<F>) => { | ||
const resolve = () => { | ||
const t = getTarget(); | ||
return (t[key] as F)(...args); | ||
}; | ||
|
||
if (!this.isomorphicClerk.loaded) { | ||
this.isomorphicClerk.addOnLoaded(resolve); | ||
return; | ||
} | ||
|
||
resolve(); | ||
}) as T[K]; | ||
} |
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.
subscribe currently drops the unsubscribe function
gateListenerMethod
does not return the underlying unsubscribe, breaking the __experimental_CheckoutInstance.subscribe
contract.
Apply:
- private gateListenerMethod<T extends object, K extends keyof T>(
- getTarget: () => T,
- key: T[K] extends (...args: any[]) => void ? K : never,
- ): T[K] {
- // This method should only be used with keys that point to void-returning functions
- type F = Extract<T[K], (...args: any[]) => void>;
- return ((...args: Parameters<F>) => {
- const resolve = () => {
- const t = getTarget();
- return (t[key] as F)(...args);
- };
-
- if (!this.isomorphicClerk.loaded) {
- this.isomorphicClerk.addOnLoaded(resolve);
- return;
- }
-
- resolve();
- }) as T[K];
- }
+ private gateListenerMethod<T extends object, K extends keyof T>(
+ getTarget: () => T,
+ key: T[K] extends (...args: any[]) => () => void ? K : never,
+ ): T[K] {
+ type F = Extract<T[K], (...args: any[]) => () => void>;
+ return ((...args: Parameters<F>) => {
+ const attach = () => {
+ const t = getTarget();
+ return (t[key] as F)(...args);
+ };
+ if (!this.isomorphicClerk.loaded) {
+ let unsubscribe: ReturnType<F> | undefined;
+ this.isomorphicClerk.addOnLoaded(() => {
+ unsubscribe = attach();
+ });
+ return (() => unsubscribe?.()) as ReturnType<F>;
+ }
+ return attach();
+ }) as T[K];
+ }
📝 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.
private gateListenerMethod<T extends object, K extends keyof T>( | |
getTarget: () => T, | |
key: T[K] extends (...args: any[]) => void ? K : never, | |
): T[K] { | |
// This method should only be used with keys that point to void-returning functions | |
type F = Extract<T[K], (...args: any[]) => void>; | |
return ((...args: Parameters<F>) => { | |
const resolve = () => { | |
const t = getTarget(); | |
return (t[key] as F)(...args); | |
}; | |
if (!this.isomorphicClerk.loaded) { | |
this.isomorphicClerk.addOnLoaded(resolve); | |
return; | |
} | |
resolve(); | |
}) as T[K]; | |
} | |
private gateListenerMethod<T extends object, K extends keyof T>( | |
getTarget: () => T, | |
key: T[K] extends (...args: any[]) => () => void ? K : never, | |
): T[K] { | |
type F = Extract<T[K], (...args: any[]) => () => void>; | |
return ((...args: Parameters<F>) => { | |
const attach = () => { | |
const t = getTarget(); | |
return (t[key] as F)(...args); | |
}; | |
if (!this.isomorphicClerk.loaded) { | |
let unsubscribe: ReturnType<F> | undefined; | |
this.isomorphicClerk.addOnLoaded(() => { | |
unsubscribe = attach(); | |
}); | |
return (() => unsubscribe?.()) as ReturnType<F>; | |
} | |
return attach(); | |
}) as T[K]; | |
} |
🤖 Prompt for AI Agents
In packages/react/src/stateProxy.ts around lines 240-259, gateListenerMethod
currently invokes the target function but discards and doesn't return its
unsubscribe value, breaking subscribe/unsubscribe semantics; modify the
implementation so the inner resolve returns the value from (t[key] as
F)(...args) and propagate that return value to callers, and when isomorphicClerk
isn't loaded addOnLoaded should register a wrapper that either returns the
eventual unsubscribe or returns a synchronous no-op/unsubscribe stub until the
real unsubscribe is available—ensure the function signature and typings reflect
the return type so callers receive the underlying unsubscribe function when
present.
export const useCheckout = (options?: Params): __experimental_UseCheckoutReturn => { | ||
const contextOptions = useCheckoutContext(); | ||
const { for: forOrganization, planId, planPeriod } = options || contextOptions; | ||
|
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.
🛠️ Refactor suggestion
Don’t hard-require Checkout provider when options are supplied
useCheckoutContext() is called unconditionally, so using useCheckout with explicit options outside the Checkout provider will still throw. Provide an optional context accessor and only fall back to context when options are absent.
Proposed change in this file (assumes a new non-throwing hook export useOptionalCheckoutContext in ../contexts):
-import { useCheckoutContext, useClerkInstanceContext } from '../contexts';
+import { useOptionalCheckoutContext, useClerkInstanceContext } from '../contexts';
- const contextOptions = useCheckoutContext();
- const { for: forOrganization, planId, planPeriod } = options || contextOptions;
+ const contextOptions = useOptionalCheckoutContext();
+ const baseOptions = options ?? contextOptions;
+ if (!baseOptions) {
+ throw new Error(
+ 'Clerk: useCheckout requires either explicit options ({ for, planId, planPeriod }) or to be rendered within <Checkout />.',
+ );
+ }
+ const { for: forOrganization, planId, planPeriod } = baseOptions;
If you’d like, I can add useOptionalCheckoutContext in ../contexts and wire it here.
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useCheckout.ts around lines 81 to 84, the
hook currently calls useCheckoutContext() unconditionally which throws when used
outside the Checkout provider even if explicit options are passed; change it to
call a non-throwing optional accessor (useOptionalCheckoutContext from
../contexts) only when options are not provided, so that when options exist you
do not invoke any context hook. Specifically: import useOptionalCheckoutContext,
grab contextOptions via that hook only if options is undefined, then derive {
for: forOrganization, planId, planPeriod } from options ?? contextOptions;
ensure no direct call to the throwing context hook in this file.
const clerk = useClerkInstanceContext(); | ||
|
||
const manager = useMemo(() => { | ||
return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization }); | ||
}, [ | ||
// user?.id, organization?.id, | ||
planId, | ||
planPeriod, | ||
forOrganization, | ||
]); |
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.
💡 Verification agent
🧩 Analysis chain
Missing dependency and potential staleness on auth/org switch
manager depends on clerk but clerk isn’t in the deps array. If the Clerk instance changes (hard reload, provider swap) the memo won’t update. Also, dropping user.id/organization?.id means the manager won’t be recreated on auth/org changes; ensure the underlying __experimental_checkout handles those transitions internally.
const manager = useMemo(() => {
return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization });
- }, [
- // user?.id, organization?.id,
- planId,
- planPeriod,
- forOrganization,
- ]);
+ }, [clerk, planId, planPeriod, forOrganization]);
Please verify that user sign-in/sign-out and active-organization switching correctly reset the checkout state without reloading the page. If not, consider reintroducing user.id and organization?.id into the deps.
🏁 Script executed:
#!/usr/bin/env bash
# Locate the hook file
file=$(fd --type f useCheckout.ts)
echo "Inspecting file: $file"
# Show the first 200 lines to review context and dependencies
sed -n '1,200p' "$file"
Length of output: 5551
Include the Clerk instance in the useMemo
deps and verify auth/org transitions
Add clerk
to the dependency array so the checkout manager is recreated when the Clerk context changes. Confirm that signing in/out and switching organizations properly resets the checkout state; if they don’t, reintroduce user?.id
and organization?.id
into the deps.
const manager = useMemo(() => {
return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization });
- }, [
- // user?.id, organization?.id,
- planId,
- planPeriod,
- forOrganization,
- ]);
+ }, [clerk, planId, planPeriod, forOrganization]);
📝 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.
const clerk = useClerkInstanceContext(); | |
const manager = useMemo(() => { | |
return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization }); | |
}, [ | |
// user?.id, organization?.id, | |
planId, | |
planPeriod, | |
forOrganization, | |
]); | |
const manager = useMemo(() => { | |
return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization }); | |
}, [clerk, planId, planPeriod, forOrganization]); |
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useCheckout.ts around lines 98 to 107, the
useMemo that creates the checkout manager omits the Clerk instance from its
dependency array which prevents the manager from being recreated when Clerk
context changes; add clerk to the dependency array so the manager is rebuilt on
Clerk instance changes, then test sign-in/sign-out and org switches to ensure
checkout state resets correctly—if those transitions still don't reset state,
reintroduce user?.id and organization?.id into the deps so the memo reacts to
auth and organization changes.
// const subscribe = useCallback( | ||
// (callback: () => void) => { | ||
// if (!clerk.loaded) { | ||
// return () => {}; | ||
// } | ||
|
||
// return manager.subscribe(callback); | ||
// }, | ||
// [clerk.loaded, manager], | ||
// ); | ||
// const getSnapshot = useCallback(() => { | ||
// return manager.getState(); | ||
// }, [manager]); | ||
|
||
const managerProperties = useSyncExternalStore(manager.subscribe, manager.getState, manager.getState); |
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.
🛠️ Refactor suggestion
Bind methods when passing to useSyncExternalStore and remove dead scaffolding
Passing bare methods risks losing this binding; also, the commented subscribe/getSnapshot code can go.
- // const subscribe = useCallback(
- // (callback: () => void) => {
- // if (!clerk.loaded) {
- // return () => {};
- // }
- //
- // return manager.subscribe(callback);
- // },
- // [clerk.loaded, manager],
- // );
- // const getSnapshot = useCallback(() => {
- // return manager.getState();
- // }, [manager]);
-
- const managerProperties = useSyncExternalStore(manager.subscribe, manager.getState, manager.getState);
+ const managerProperties = useSyncExternalStore(
+ cb => manager.subscribe(cb),
+ () => manager.getState(),
+ () => manager.getState(),
+ );
📝 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.
// const subscribe = useCallback( | |
// (callback: () => void) => { | |
// if (!clerk.loaded) { | |
// return () => {}; | |
// } | |
// return manager.subscribe(callback); | |
// }, | |
// [clerk.loaded, manager], | |
// ); | |
// const getSnapshot = useCallback(() => { | |
// return manager.getState(); | |
// }, [manager]); | |
const managerProperties = useSyncExternalStore(manager.subscribe, manager.getState, manager.getState); | |
const managerProperties = useSyncExternalStore( | |
cb => manager.subscribe(cb), | |
() => manager.getState(), | |
() => manager.getState(), | |
); |
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useCheckout.ts around lines 109 to 123, the
call to useSyncExternalStore currently passes unbound manager methods which will
lose their this binding and the commented subscribe/getSnapshot scaffolding is
dead code; fix by removing the commented subscribe/getSnapshot block and pass
bound functions to useSyncExternalStore (e.g., subscribe and getState bound to
manager) so the methods execute with the correct receiver, ensuring the
fallback/getSnapshot arguments are the bound getState.
Description
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Bug Fixes
Refactor