Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Sep 5, 2025

Description

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Added a checkout signal API enabling start/confirm/subscribe/getState with safe fallbacks, including pre-load and SSR scenarios.
  • Bug Fixes

    • Prevented crashes when ClerkJS isn’t loaded by falling back to a safe checkout signal.
    • Reduced premature errors during loading; validation now waits until data is ready.
    • Corrected checkout readiness checks to use plan/status/totals instead of IDs.
  • Refactor

    • Switched checkout hook to a context-based Clerk instance and simplified subscription/state management for more reliable updates.

Copy link

changeset-bot bot commented Sep 5, 2025

⚠️ No Changeset found

Latest commit: fb46eb8

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

Copy link

vercel bot commented Sep 5, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 5, 2025 6:15pm

Copy link
Contributor

coderabbitai bot commented Sep 5, 2025

Walkthrough

The 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

Cohort / File(s) Summary
UI checkout gating updates
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
Replaced id-based guards with plan/totals/status checks in CheckoutForm, useCheckoutMutations, and CheckoutFormElements; removed destructured id usage.
Isomorphic delegation for checkout
packages/react/src/isomorphicClerk.ts
__experimental_checkout now branches: calls ClerkJS when loaded; otherwise falls back to StateProxy.checkoutSignal.
StateProxy checkout API and gating
packages/react/src/stateProxy.ts
Added public StateProxy.checkoutSignal(params) returning __experimental_CheckoutInstance; implemented buildCheckoutProxy with confirm/start/clear/finalize/subscribe/getState; added gating helpers and server/browser readiness handling; expanded types/imports.
useCheckout hook plumbing
packages/shared/src/react/hooks/useCheckout.ts
Switched to useClerkInstanceContext; refined error timing (only post-load); organization checks gated by isLoaded; memo deps simplified; useSyncExternalStore simplified to manager.subscribe/getState.

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
Loading
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
Loading
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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

A rabbit taps the checkout key,
Proxies bloom where loaders be.
If Clerk naps, a signal wakes—
Guarded gates for careful takes.
Plans, not ids, now lead the run,
Context hums, the wiring’s done.
Thump-thump—ship it, on the run! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/bill-1098-update-usecheckout-and-usepaymentelement-to-not-require

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@panteliselef panteliselef changed the title Elef/bill 1098 update usecheckout and usepaymentelement to not require chore(shared,clerk-react): Support useCheckout while clerk-js still loads Sep 5, 2025
Copy link

pkg-pr-new bot commented Sep 5, 2025

Open in StackBlitz

@clerk/agent-toolkit

npm i https://pkg.pr.new/@clerk/agent-toolkit@6720

@clerk/astro

npm i https://pkg.pr.new/@clerk/astro@6720

@clerk/backend

npm i https://pkg.pr.new/@clerk/backend@6720

@clerk/chrome-extension

npm i https://pkg.pr.new/@clerk/chrome-extension@6720

@clerk/clerk-js

npm i https://pkg.pr.new/@clerk/clerk-js@6720

@clerk/dev-cli

npm i https://pkg.pr.new/@clerk/dev-cli@6720

@clerk/elements

npm i https://pkg.pr.new/@clerk/elements@6720

@clerk/clerk-expo

npm i https://pkg.pr.new/@clerk/clerk-expo@6720

@clerk/expo-passkeys

npm i https://pkg.pr.new/@clerk/expo-passkeys@6720

@clerk/express

npm i https://pkg.pr.new/@clerk/express@6720

@clerk/fastify

npm i https://pkg.pr.new/@clerk/fastify@6720

@clerk/localizations

npm i https://pkg.pr.new/@clerk/localizations@6720

@clerk/nextjs

npm i https://pkg.pr.new/@clerk/nextjs@6720

@clerk/nuxt

npm i https://pkg.pr.new/@clerk/nuxt@6720

@clerk/clerk-react

npm i https://pkg.pr.new/@clerk/clerk-react@6720

@clerk/react-router

npm i https://pkg.pr.new/@clerk/react-router@6720

@clerk/remix

npm i https://pkg.pr.new/@clerk/remix@6720

@clerk/shared

npm i https://pkg.pr.new/@clerk/shared@6720

@clerk/tanstack-react-start

npm i https://pkg.pr.new/@clerk/tanstack-react-start@6720

@clerk/testing

npm i https://pkg.pr.new/@clerk/testing@6720

@clerk/themes

npm i https://pkg.pr.new/@clerk/themes@6720

@clerk/types

npm i https://pkg.pr.new/@clerk/types@6720

@clerk/upgrade

npm i https://pkg.pr.new/@clerk/upgrade@6720

@clerk/vue

npm i https://pkg.pr.new/@clerk/vue@6720

commit: fb46eb8

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 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 on plan 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-label

Per 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: Validate payment_source_id before confirming

Defensive 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 API

Re-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 memoize

This 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 informative

Throwing '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: Verify shouldDefaultBeUsed 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 type

Add 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 immutability

Optional: 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 proxy

Dead/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 block

Dead/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 hook

Public 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.

📥 Commits

Reviewing files that changed from the base of the PR and between aa098bd and fb46eb8.

📒 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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly 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
Use const assertions for literal types: as const
Use satisfies 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 ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly 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 to isomorphicClerk.__experimental_checkout. Since buildCheckoutProxy 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 retrieval

Using useClerkInstanceContext reduces coupling to the React package and plays nicer with isomorphic usage.


88-91: Better error timing

Throwing only when isLoaded and no user avoids premature errors during hydration/SSR.


92-96: Org-guard after load is correct

Validating forOrganization === 'organization' only after load prevents false positives. Message is actionable.

Comment on lines 189 to +197
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) {
Copy link
Contributor

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.

Suggested change
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'.

Comment on lines 737 to 741
__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);
};
Copy link
Contributor

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.

Suggested change
__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.

Comment on lines +240 to +259
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];
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

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.

Suggested change
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.

Comment on lines 81 to 84
export const useCheckout = (options?: Params): __experimental_UseCheckoutReturn => {
const contextOptions = useCheckoutContext();
const { for: forOrganization, planId, planPeriod } = options || contextOptions;

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

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.

Comment on lines +98 to +107
const clerk = useClerkInstanceContext();

const manager = useMemo(() => {
return clerk.__experimental_checkout({ planId, planPeriod, for: forOrganization });
}, [
// user?.id, organization?.id,
planId,
planPeriod,
forOrganization,
]);
Copy link
Contributor

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.

Suggested change
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.

Comment on lines +109 to +123
// 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);
Copy link
Contributor

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.

Suggested change
// 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.

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

Successfully merging this pull request may close these issues.

2 participants