Skip to content

Conversation

@mauricioabreu
Copy link
Contributor

@mauricioabreu mauricioabreu commented Oct 24, 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

    • Free trials can now be started without providing a payment method.
  • UI Changes

    • Checkout and confirmation screens adjust messaging, buttons, and payment-method display based on whether a payment method is required.
  • Types

    • Public API exposes a flag indicating whether a payment method is required for checkout.
  • Tests

    • Expanded coverage for free-trial and checkout/payment-method scenarios.
  • Chores

    • Package version bumps and increased bundle size limit for checkout assets.

@changeset-bot
Copy link

changeset-bot bot commented Oct 24, 2025

🦋 Changeset detected

Latest commit: 8095cff

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 22 packages
Name Type
@clerk/clerk-js Minor
@clerk/types Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/localizations Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/shared Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/themes Patch
@clerk/vue Patch

Not sure what this means? Click here to learn what changesets are.

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

@vercel
Copy link

vercel bot commented Oct 24, 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 Oct 25, 2025 1:21pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 24, 2025

Walkthrough

Adds a boolean needsPaymentMethod to billing types and JSON, surfaces it in the Checkout resource, updates checkout UI and mutations to support starting free trials without a payment method, makes billing test fixtures configurable, and expands tests for free-trial/payment flows. Includes changeset and bundlewatch size bump.

Changes

Cohort / File(s) Summary
Changeset & Config
\.changeset/bumpy-glasses-eat.md, packages/clerk-js/bundlewatch.config.json
New changeset documenting minor package bumps and the "make payment method optional for free trials" feature; increased checkout*.js bundle size limit from ~8.77KB to 10KB.
Core Resource & Types
packages/clerk-js/src/core/resources/BillingCheckout.ts, packages/types/src/billing.ts, packages/types/src/json.ts
Added needsPaymentMethod / needs_payment_method to BillingCheckout resource, BillingCheckoutResource type, and JSON interface; deserialization maps data.needs_payment_method into the resource.
Checkout UI & Mutations
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx, packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
Introduced payWithoutPaymentMethod mutation and UI wiring; added FreeTrialButton and CheckoutSubmitButton; refactored conditional rendering to use needsPaymentMethod; adjusted payment-method display/fallbacks and form styling/props.
Tests & Fixtures
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx, packages/clerk-js/src/test/fixture-helpers.ts, packages/shared/src/react/hooks/useCheckout.ts
Tests updated/added to cover free-trial and payment flows using needsPaymentMethod; withBilling fixture helper became configurable with options; initial null-checkout payload now includes needsPaymentMethod.

Sequence Diagram

sequenceDiagram
    participant User
    participant CheckoutUI as "CheckoutForm / Components"
    participant API as "Backend / Mutations"

    rect #F0F4C3
      note left of CheckoutUI: Decision based on needsPaymentMethod
    end

    alt needsPaymentMethod == true
        User->>CheckoutUI: Open checkout
        CheckoutUI->>User: Show payment-method UI
        User->>CheckoutUI: Select/add payment method
        User->>CheckoutUI: Submit (Pay)
        CheckoutUI->>API: confirmCheckout(payment_method_id)
        API-->>CheckoutUI: success
        CheckoutUI-->>User: Confirmation
    else needsPaymentMethod == false
        User->>CheckoutUI: Open checkout
        CheckoutUI->>User: Show Start Trial (no payment UI)
        User->>CheckoutUI: Click Start Trial
        CheckoutUI->>API: confirmCheckout() / payWithoutPaymentMethod()
        API-->>CheckoutUI: trial started
        CheckoutUI-->>User: Confirmation
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Review CheckoutForm.tsx & CheckoutComplete.tsx conditional logic and new submit flows (payWithoutPaymentMethod).
  • Verify deserialization and type additions in BillingCheckout / types / json.
  • Check tests in Checkout.test.tsx for correct fixture updates and coverage.
  • Inspect fixture-helpers withBilling signature change and any callers.

Poem

🐇
I nibbled code beneath the moon,
A tiny flag to change things soon.
Trials now hop without a card,
Users smile — the change isn’t hard.
Hooray, says Rabbit, soft and starred 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat(clerk-js,types): Make payment method optional for free trials" clearly and directly describes the main feature being implemented across the changeset. The title accurately reflects the core changes: adding a new needsPaymentMethod boolean field to BillingCheckout and types, updating checkout UI components to use this field, and enabling a free trial payment flow without requiring a payment method. The title is specific, concise, uses proper conventional commit formatting, specifies affected packages, and avoids vague or generic language. A teammate scanning the commit history would immediately understand that this PR enables optional payment methods for free trial scenarios.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials

📜 Recent 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.

📥 Commits

Reviewing files that changed from the base of the PR and between eb24790 and 8095cff.

📒 Files selected for processing (3)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
🧰 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/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • 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/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • 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/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
  • Drawer (561-570)
packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
  • Checkout (12-62)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
  • useCheckoutContext (10-37)
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/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
packages/clerk-js/src/ui/styledSystem/types.ts (2)
  • PropsOfComponent (58-58)
  • ThemableCssProp (58-58)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-148)
⏰ 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). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (13)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (7)

370-370: LGTM: needsPaymentMethod field added to test fixtures.

The needsPaymentMethod field is correctly set across existing test fixtures, aligning with their scenarios: false for free trials and downgrades, true for paid subscriptions requiring payment methods.

Also applies to: 455-455, 550-550, 642-642


800-802: LGTM: Assertion correctly validates needsPaymentMethod=true behavior.

The test properly asserts that when needsPaymentMethod is true, the "Subscribe" button is shown instead of "Start free trial", aligning with the feature requirements.


941-944: LGTM: Minor refactor improves readability.

Storing the Pay button query in a variable before asserting is a good practice for test clarity.


946-1050: LGTM: Test correctly validates free trial requiring payment method.

The test properly verifies that when a free trial requires a payment method (needsPaymentMethod: true), the "Subscribe" button is shown in the "Add payment method" tab, which aligns with the expected behavior.


1052-1143: LGTM: Test correctly validates payment method requirement with no stored methods.

The test properly verifies that when needsPaymentMethod: true but no payment methods exist, the UI directly shows payment collection without segmented controls, and displays the "Subscribe" button. This aligns with the expected UX flow.


1145-1240: LGTM: Test validates core feature - free trial without payment method.

This test correctly verifies the primary feature: when needsPaymentMethod: false, the UI hides all payment method controls (tabs, inputs) and shows only the "Start free trial" button, enabling frictionless trial starts.


1242-1351: LGTM: Test validates important edge case with stored payment methods.

This test ensures that when needsPaymentMethod: false, the UI completely hides payment method controls even when stored payment methods exist. This confirms that the flag properly overrides payment method display logic, which is critical for the feature.

packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6)

2-2: LGTM: Import additions support new functionality.

The added type imports (ConfirmCheckoutParams, PropsOfComponent, ThemableCssProp) are properly utilized in the file for type safety and component composition.

Also applies to: 18-18


142-142: LGTM: payWithoutPaymentMethod implementation is clean.

The new function correctly handles free trial submissions without payment methods by calling confirmCheckout({}) with empty parameters. It follows the established pattern of other payment mutation functions and integrates properly with the onSubscriptionComplete callback.

Also applies to: 176-179, 193-193


222-222: LGTM: Rendering logic correctly prioritizes needsPaymentMethod.

The refactored conditional logic properly handles all scenarios:

  • needsPaymentMethod=false → Shows FreeTrialButton (no payment UI)
  • needsPaymentMethod=true → Shows appropriate payment form based on paymentMethodSource and available payment methods

The logic correctly addresses the past review concerns by checking needsPaymentMethod first, ensuring free trials without payment requirements bypass all payment UI.

Also applies to: 229-229, 243-243, 264-270


334-334: LGTM: Submit label logic correctly reflects payment requirements.

The refactored useSubmitLabel properly prioritizes needsPaymentMethod:

  • When true: Shows payment-specific labels ("Pay $X.XX" or "Subscribe")
  • When false with trial: Shows "Start free trial"
  • Fallback: "Subscribe"

This ensures button labels accurately communicate the action to users.

Also applies to: 340-356


393-417: LGTM: New components promote code reuse and consistency.

CheckoutSubmitButton and formProps are well-designed utilities that:

  • Centralize submit button rendering with proper loading states and labels
  • Provide consistent form styling across payment flows
  • Support extensibility through props spreading

420-420: LGTM: ExistingPaymentMethodForm properly integrates needsPaymentMethod.

The updates correctly:

  • Use needsPaymentMethod to conditionally show payment method selection UI
  • Handle both immediate upgrades (show select) and downgrades (hidden input only)
  • Apply consistent styling via formProps and CheckoutSubmitButton

Also applies to: 422-422, 444-444, 449-449, 492-492


Comment @coderabbitai help to get the list of available commands and usage tips.

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from ec36e8d to db232df Compare October 24, 2025 21:05
@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from db232df to f122be2 Compare October 24, 2025 21:06
@mauricioabreu mauricioabreu changed the title Mauricio antunes/bill 1298 make requiring a credit card a toggle for free trials feat(clerk-js): Remove the requirement to add a payment method when subscribing to free trials, depending on a flag Oct 24, 2025
@mauricioabreu mauricioabreu changed the title feat(clerk-js): Remove the requirement to add a payment method when subscribing to free trials, depending on a flag feat(clerk-js,types): Make payment method optional for free trials Oct 24, 2025
@mauricioabreu mauricioabreu marked this pull request as ready for review October 24, 2025 21:36
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: 0

🧹 Nitpick comments (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)

352-366: Remove unused variable _for.

The variable destructured on line 353 is never used in the component. Consider removing it to keep the code clean.

Apply this diff:

 const FreeTrialButton = withCardStateProvider(() => {
-  const { for: _for } = useCheckoutContext();
   const { payWithoutPaymentMethod } = useCheckoutMutations();
   const card = useCardState();

413-489: Consider simplifying showPaymentMethods logic.

In ExistingPaymentMethodForm, line 438 sets showPaymentMethods = needsPaymentMethod. However, this component is only rendered when needsPaymentMethod is already true (line 264). This means:

  • showPaymentMethods is always true inside this component
  • The else branch (lines 479-483) is unreachable

You have two options:

  1. Remove the conditional and always render the Select component
  2. If the hidden input fallback serves a purpose, document why it's needed

Option 1 - Remove redundant conditional:

 const ExistingPaymentMethodForm = withCardStateProvider(
   ({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {
     const { checkout } = useCheckout();
-    const { paymentMethod, needsPaymentMethod } = checkout;
+    const { paymentMethod } = checkout;

     const { payWithExistingPaymentMethod } = useCheckoutMutations();
     const card = useCardState();
     const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<BillingPaymentMethodResource | undefined>(
       paymentMethod || paymentMethods.find(p => p.isDefault),
     );

     const options = useMemo(() => {
       return paymentMethods.map(method => {
         const label =
           method.paymentType !== 'card'
             ? `${capitalize(method.paymentType)}`
             : `${capitalize(method.cardType)} ⋯ ${method.last4}`;

         return {
           value: method.id,
           label,
         };
       });
     }, [paymentMethods]);

-    const showPaymentMethods = needsPaymentMethod;

     return (
       <Form
         onSubmit={payWithExistingPaymentMethod}
         sx={formProps}
       >
-        {showPaymentMethods ? (
-          <Select
-            elementId='paymentMethod'
-            options={options}
-            value={selectedPaymentMethod?.id || null}
-            onChange={option => {
-              const paymentMethod = paymentMethods.find(source => source.id === option.value);
-              setSelectedPaymentMethod(paymentMethod);
-            }}
-            portal
-          >
-            {/*Store value inside an input in order to be accessible as form data*/}
-            <input
-              name={HIDDEN_INPUT_NAME}
-              type='hidden'
-              value={selectedPaymentMethod?.id}
-            />
-            <SelectButton
-              icon={ChevronUpDown}
-              sx={t => ({
-                justifyContent: 'space-between',
-                backgroundColor: t.colors.$colorBackground,
-              })}
-            >
-              {selectedPaymentMethod && <PaymentMethodRow paymentMethod={selectedPaymentMethod} />}
-            </SelectButton>
-            <SelectOptionList
-              sx={t => ({
-                paddingBlock: t.space.$1,
-                color: t.colors.$colorForeground,
-              })}
-            />
-          </Select>
-        ) : (
+        <Select
+          elementId='paymentMethod'
+          options={options}
+          value={selectedPaymentMethod?.id || null}
+          onChange={option => {
+            const paymentMethod = paymentMethods.find(source => source.id === option.value);
+            setSelectedPaymentMethod(paymentMethod);
+          }}
+          portal
+        >
+          {/*Store value inside an input in order to be accessible as form data*/}
           <input
             name={HIDDEN_INPUT_NAME}
             type='hidden'
             value={selectedPaymentMethod?.id}
           />
-        )}
+          <SelectButton
+            icon={ChevronUpDown}
+            sx={t => ({
+              justifyContent: 'space-between',
+              backgroundColor: t.colors.$colorBackground,
+            })}
+          >
+            {selectedPaymentMethod && <PaymentMethodRow paymentMethod={selectedPaymentMethod} />}
+          </SelectButton>
+          <SelectOptionList
+            sx={t => ({
+              paddingBlock: t.space.$1,
+              color: t.colors.$colorForeground,
+            })}
+          />
+        </Select>
         <Card.Alert>{card.error}</Card.Alert>
         <CheckoutSubmitButton />
       </Form>
     );
   },
 );
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between d1a186c and 1eea4c6.

📒 Files selected for processing (8)
  • .changeset/bumpy-glasses-eat.md (1 hunks)
  • packages/clerk-js/bundlewatch.config.json (1 hunks)
  • packages/clerk-js/src/core/resources/BillingCheckout.ts (2 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (1 hunks)
  • packages/types/src/billing.ts (1 hunks)
  • packages/types/src/json.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (14)
**/*.{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/types/src/json.ts
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/types/src/json.ts
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/bundlewatch.config.json
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/types/src/json.ts
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/types/src/json.ts
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
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/types/src/json.ts
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/types/src/json.ts
  • packages/types/src/billing.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
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/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
.changeset/**

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/bumpy-glasses-eat.md
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
  • Drawer (561-570)
packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
  • Checkout (12-62)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
  • useCheckoutContext (10-37)
packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
packages/types/src/billing.ts (1)
  • BillingPaymentMethodResource (277-332)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-147)
🔇 Additional comments (19)
packages/clerk-js/bundlewatch.config.json (1)

27-27: LGTM! Reasonable bundle size increase.

The ~1.23KB increase in the checkout bundle size is expected given the addition of:

  • New needsPaymentMethod flag and related logic
  • New internal components (FreeTrialButton, CheckoutSubmitButton)
  • Enhanced conditional rendering for free trial flows
.changeset/bumpy-glasses-eat.md (1)

1-6: LGTM! Changeset follows conventions.

The changeset correctly specifies minor version bumps for both packages and provides a clear description of the feature.

packages/types/src/json.ts (1)

818-818: LGTM! JSON DTO field addition follows conventions.

The needs_payment_method field follows the snake_case naming convention used throughout the JSON DTOs and aligns with the camelCase needsPaymentMethod in the TypeScript interface.

packages/types/src/billing.ts (1)

782-786: LGTM! Well-documented public API addition.

The needsPaymentMethod field is properly documented with clear JSDoc explaining its purpose and usage. The addition is straightforward and follows the existing interface patterns.

packages/clerk-js/src/core/resources/BillingCheckout.ts (2)

32-32: LGTM! Property declaration follows class conventions.

The property declaration is consistent with other boolean flags in the class.


56-56: LGTM! Deserialization follows existing patterns.

The mapping from data.needs_payment_method to this.needsPaymentMethod is consistent with how other fields are deserialized in the fromJSON method.

packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2)

164-164: LGTM! New field destructured for conditional UI logic.

The needsPaymentMethod field is appropriately extracted from the checkout object to drive subsequent rendering decisions.


431-451: LGTM! Clearer conditional logic with needsPaymentMethod.

The refactored conditionals using needsPaymentMethod are more explicit and maintainable than the previous logic based on totals.totalDueNow.amount > 0 || freeTrialEndsAt !== null. The code properly handles the case when paymentMethod is undefined with a fallback to '–'.

packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (5)

934-937: LGTM! Minor test improvement.

Extracting the button to a variable before assertion improves readability and follows good testing practices.


939-1042: LGTM! Comprehensive free trial test coverage.

This test effectively verifies the "Add payment method" tab behavior during free trials, including:

  • Proper button text ("Start free trial")
  • Tab switching behavior
  • UI state when payment methods exist but aren't required

1044-1133: LGTM! Edge case properly tested.

This test validates the scenario where no payment methods exist but the free trial requires adding one, ensuring the UI correctly prompts the user while hiding unnecessary controls.


1135-1229: LGTM! Important edge case covered.

This test confirms that when needsPaymentMethod is false, the payment method UI is completely hidden (no segmented controls, no hidden inputs), and only the "Start free trial" button is shown.


1231-1339: LGTM! Critical test for free trial isolation.

This test ensures that even when stored payment methods exist, they are not displayed or used when needsPaymentMethod is false. This properly validates that free trials can proceed without payment method collection when configured that way.

packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6)

2-2: LGTM! Unused import removed.

Good cleanup removing the BillingMoneyAmount type that is no longer used in the file.


176-179: LGTM! New mutation handler for free trials without payment methods.

The payWithoutPaymentMethod handler correctly confirms checkout without requiring payment data, enabling free trials that don't need upfront payment method collection.


241-258: LGTM! Segmented control properly gated by needsPaymentMethod.

The conditional ensures the payment method source selector is only shown when:

  1. Payment methods exist
  2. Payment method is actually needed
  3. RHC (React Headless Components) is not disabled

262-269: LGTM! Clear branching logic based on needsPaymentMethod.

The refactored conditional is straightforward:

  • When payment method is needed: show existing or new payment method forms
  • When not needed: show free trial button

This is much clearer than the previous totals-based logic.


387-405: LGTM! Reusable submit button component.

The CheckoutSubmitButton component appropriately consolidates the common submit button configuration (localization, loading state, full width) used across multiple forms.


407-411: LGTM! Shared styling helper.

The formProps helper provides consistent vertical layout styling across all checkout forms.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 24, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 8095cff

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: 1

🧹 Nitpick comments (7)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (7)

639-640: Good coverage for needsPaymentMethod; consider DRYing the fixtures.

Adding needsPaymentMethod in mocks across scenarios is correct and aligns tests with the new API surface. To reduce duplication and maintenance, extract a small builder (e.g., buildCheckout(overrides) and buildPlan(overrides)) and reuse across tests.

Also applies to: 752-753, 892-893, 1109-1110, 1199-1200, 1303-1304, 1435-1436


937-939: Avoid brittle exact currency label match.

Exact "Pay $10.00" can fail under locale/spacing differences. Prefer a regex and case-insensitive match.

-        const payButton = getByRole('button', { name: 'Pay $10.00' });
-        expect(payButton).toBeInTheDocument();
+        expect(getByRole('button', { name: /pay\s*\$?\s*10\.00/i })).toBeInTheDocument();

942-1045: Move userEvent outside waitFor to reduce flakiness.

Trigger events first, then wait for resulting assertions. Avoid invoking userEvent inside waitFor.

-      await waitFor(async () => {
-        expect(getByRole('heading', { name: 'Checkout' })).toBeVisible();
-        const addPaymentMethodButton = getByText('Add payment method');
-        expect(addPaymentMethodButton).toBeVisible();
-        await userEvent.click(addPaymentMethodButton);
-      });
+      expect(getByRole('heading', { name: 'Checkout' })).toBeVisible();
+      const addPaymentMethodButton = getByText('Add payment method');
+      expect(addPaymentMethodButton).toBeVisible();
+      await userEvent.click(addPaymentMethodButton);
+      await waitFor(() => {
+        expect(getByRole('button', { name: 'Start free trial' })).toBeInTheDocument();
+      });

1138-1232: Solid scenarios for “free trial, not required” with/without stored PMs; minor robustness nits.

These cover the no-prompt path well. For resilience:

  • Prefer case-insensitive queries for brand strings when present/absent checks: use /visa/i.
  • Where asserting absence of tabs, also assert queryByRole('tablist') is null to decouple from labels.

Also applies to: 1234-1341


1330-1334: Card brand match should be case-insensitive.

UI may render “Visa” vs “visa”. Use a regex.

-        const visaPaymentMethod = queryByText('visa');
+        const visaPaymentMethod = queryByText(/visa/i);
         expect(visaPaymentMethod).toBeNull();

-        const last4Digits = queryByText('⋯ 4242');
+        const last4Digits = queryByText(/⋯\s*4242/)
         expect(last4Digits).toBeNull();

942-1045: Reduce fixture duplication with small builders.

The large repeated startCheckout and plan payloads make updates error-prone. Extract a builder to keep tests concise and consistent.

// top of file (outside tests)
const basePlan = {
  id: 'plan_trial',
  name: 'Pro',
  description: 'Pro plan',
  features: [],
  fee: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' },
  annualFee: { amount: 12000, amountFormatted: '120.00', currency: 'USD', currencySymbol: '$' },
  annualMonthlyFee: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' },
  slug: 'pro',
  avatarUrl: '',
  publiclyVisible: true,
  isDefault: true,
  isRecurring: true,
  hasBaseFee: false,
  forPayerType: 'user',
  freeTrialDays: 7,
  freeTrialEnabled: true,
} as const;

const baseCheckout = {
  externalClientSecret: 'cs_test',
  externalGatewayId: 'gw_test',
  totals: {
    subtotal: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' },
    grandTotal: { amount: 1000, amountFormatted: '10.00', currency: 'USD', currencySymbol: '$' },
    taxTotal: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' },
    credit: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' },
    pastDue: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' },
    totalDueNow: { amount: 0, amountFormatted: '0.00', currency: 'USD', currencySymbol: '$' },
  },
  isImmediatePlanChange: true,
  planPeriod: 'month',
  plan: basePlan,
  paymentMethod: undefined,
  confirm: vi.fn(),
} as const;

function buildCheckout(overrides: Partial<typeof baseCheckout> = {}) {
  return { id: 'chk_test', status: 'needs_confirmation', freeTrialEndsAt: null, ...baseCheckout, ...overrides };
}

Also applies to: 1047-1136, 1138-1232, 1234-1341


639-640: I need to check the test file structure to understand why as any is being used and whether it's necessary:

Based on my verification of the codebase:

The needsPaymentMethod property is correctly integrated across all layers:

  • ✅ Public types: packages/types/src/billing.ts:786
  • ✅ JSON wire shape: packages/types/src/json.ts:818 (needs_payment_method)
  • ✅ Resource mapping: packages/clerk-js/src/core/resources/BillingCheckout.ts:56 (properly maps from wire format)
  • ✅ Hook state: packages/shared/src/react/hooks/useCheckout.ts:116
  • ✅ UI components: properly destructured and used in CheckoutComplete.tsx and CheckoutForm.tsx

However, the underlying concern in your review is valid from a testing best practice perspective: using any type on mocks is a poor choice as there would be no relationship between mock and its actual type. TypeScript's Partial utility type allows you to create mock objects while keeping all properties optional, which is particularly useful when working with partial updates or constructing objects incrementally.

Refactor test fixture objects to use Partial<BillingCheckout> with a factory function instead of as any.

This improves type safety and maintains type checking while allowing partial mocking. The pattern is used throughout the test file at lines 639–640, 752–753, 892–893, 1109–1110, 1199–1200, 1303–1304, and 1435–1436.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a244b5c and 2faf282.

📒 Files selected for processing (2)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧰 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/components/Checkout/__tests__/Checkout.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/components/Checkout/__tests__/Checkout.test.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
  • Drawer (561-570)
packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
  • Checkout (12-62)
⏰ 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). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

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: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

393-417: LGTM: Well-refactored submit button and shared form styling.

  • CheckoutSubmitButton extracts repeated logic with proper typing via PropsOfComponent
  • formProps ensures consistent vertical layout across all checkout forms
  • Both follow coding guidelines for reusable components and styling patterns
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 2faf282 and 1635921.

📒 Files selected for processing (2)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (5 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/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
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/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • 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/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • 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/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
  • Drawer (561-570)
packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
  • Checkout (12-62)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (5)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
  • useCheckoutContext (10-37)
packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
packages/clerk-js/src/ui/styledSystem/types.ts (2)
  • PropsOfComponent (58-58)
  • ThemableCssProp (58-58)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-148)
packages/shared/src/react/hooks/index.ts (1)
  • useCheckout (16-16)
⏰ 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: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (4)

639-639: LGTM: needsPaymentMethod fixtures align with test scenarios.

The additions of needsPaymentMethod: true to these test fixtures correctly reflect scenarios where payment methods are required.

Also applies to: 752-752, 892-892


937-940: LGTM: Minor test refactor for clarity.

Storing the Pay button in a variable before asserting is a good practice for test readability.


942-1136: LGTM: Comprehensive free trial test coverage.

These two tests effectively cover the "Add payment method" flow for free trials:

  • First test: When PMs exist, user can switch to "Add payment method" tab
  • Second test: When no PMs exist and PM is required, the payment form is shown directly

The previous issue flagged in review comments has been resolved (needsPaymentMethod correctly set to true).


1138-1342: Test expectations define important behavioral distinction.

These tests establish that when needsPaymentMethod: false:

  • Free trials (Line 1234, isImmediatePlanChange: true): Should NOT collect payment method at all—no hidden input (Line 1337)
  • Downgrades (Line 1344, isImmediatePlanChange: false): Should silently collect payment method via hidden input (Line 1474)

Ensure the implementation in CheckoutForm.tsx correctly differentiates these scenarios.

packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4)

2-2: LGTM: Import additions support new functionality.

The new type imports are properly utilized:

  • ConfirmCheckoutParams at Line 151
  • PropsOfComponent and ThemableCssProp at Lines 393 and 413

Also applies to: 18-18


176-179: LGTM: payWithoutPaymentMethod mutation correctly implements no-PM flow.

The implementation correctly handles free-trial checkout when no payment method is required by calling confirmCheckout({}) with no parameters.

Also applies to: 193-193


358-372: LGTM: FreeTrialButton component follows established patterns.

The component is well-structured, using:

  • withCardStateProvider for state management
  • Card.Alert for error display
  • Shared formProps styling for consistency
  • Reusable CheckoutSubmitButton

As per coding guidelines.


420-495: Conditional approval: ExistingPaymentMethodForm refactoring is sound IF rendering logic is fixed.

The refactoring is well-executed:

  • Destructured props signature (Line 420)
  • showPaymentMethods = needsPaymentMethod cleanly controls UI visibility (Line 444)
  • Hidden input at Lines 485-489 supports downgrade scenario
  • Shared formProps styling and CheckoutSubmitButton maintain consistency

However, this component assumes it's only rendered when appropriate. The critical bug at Lines 262-278 must be fixed first to ensure this component is never rendered for free trials when needsPaymentMethod: false.

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from 1635921 to 9c68ff1 Compare October 25, 2025 02:41
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: 1

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1635921 and 9c68ff1.

📒 Files selected for processing (7)
  • packages/clerk-js/src/core/resources/BillingCheckout.ts (2 hunks)
  • packages/clerk-js/src/test/fixture-helpers.ts (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (12 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (8 hunks)
  • packages/types/src/billing.ts (1 hunks)
  • packages/types/src/json.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
  • packages/types/src/billing.ts
🧰 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/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.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/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/test/fixture-helpers.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/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/test/fixture-helpers.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/test/fixture-helpers.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/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/test/fixture-helpers.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/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/test/fixture-helpers.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/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • packages/clerk-js/src/test/fixture-helpers.ts
**/*.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
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.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/Checkout/__tests__/Checkout.test.tsx
🧬 Code graph analysis (3)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (5)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
  • useCheckoutContext (10-37)
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/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
packages/clerk-js/src/ui/styledSystem/types.ts (2)
  • PropsOfComponent (58-58)
  • ThemableCssProp (58-58)
packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (1)
packages/clerk-js/src/ui/elements/LineItems.tsx (1)
  • LineItems (289-294)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (2)
packages/clerk-js/src/ui/elements/Drawer.tsx (1)
  • Drawer (561-570)
packages/clerk-js/src/ui/components/Checkout/index.tsx (1)
  • Checkout (12-62)
⏰ 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 (9)
packages/clerk-js/src/test/fixture-helpers.ts (1)

365-380: LGTM! Enhanced test fixture flexibility.

The parameterized withBilling function provides better control over billing configuration in tests, allowing selective enablement of user/organization billing and paid plans. The default values (all true) maintain backward compatibility for existing tests while enabling more granular scenarios.

packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (2)

164-164: LGTM! New flag integrated correctly.

The needsPaymentMethod flag is properly destructured and used to control the completion screen display logic.


431-451: LGTM! Conditional rendering handles both free trial and payment flows.

The logic correctly switches between:

  • Payment method details when needsPaymentMethod is true
  • Subscription start date when needsPaymentMethod is false

Appropriate fallbacks ('–') are provided when data is unavailable.

packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (3)

176-179: LGTM! Simple mutation for free trials without payment methods.

The payWithoutPaymentMethod function correctly confirms checkout without a payment source, enabling frictionless free trial activation.


358-372: LGTM! Free trial button properly integrated.

The FreeTrialButton component correctly:

  • Wraps submission in a form with payWithoutPaymentMethod handler
  • Uses shared CheckoutSubmitButton for consistency
  • Displays errors via Card.Alert
  • Applies shared formProps styling

393-417: LGTM! Reusable submit button with shared styling.

The CheckoutSubmitButton and formProps provide consistent styling and behavior across all checkout forms.

packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (3)

312-394: LGTM! Comprehensive free trial confirmation stage test.

Properly validates:

  • Free trial badge display
  • "Total Due after trial ends in N days" line item
  • "Start free trial" button presence
  • All with needsPaymentMethod: false

945-1139: LGTM! Extensive free trial flow coverage.

These three new tests comprehensively validate:

  1. Add payment method tab shows "Start free trial" for trials requiring PM
  2. Free trial prompts for PM when none exists and PM is required
  3. Free trial bypasses PM collection when PM is not required

The assertions correctly verify tab visibility, button labels, and absence of hidden payment_method_id inputs when PM is not needed.


1141-1347: LGTM! Critical free trial scenarios validated.

These tests verify:

  1. No PM prompts when needsPaymentMethod: false (Lines 1141-1236)
  2. No PM prompts even with stored PMs when not required (Lines 1238-1347)

Both correctly assert:

  • Segmented controls are hidden
  • No hidden payment_method_id input
  • "Start free trial" button renders

Note: These tests likely pass because __BUILD_DISABLE_RHC__ defaults to true in the test environment, which makes paymentMethodSource default to 'existing' (Line 226 in CheckoutForm.tsx). The rendering bug I flagged would surface in production when RHC is enabled.

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: 1

🧹 Nitpick comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

265-271: LGTM: Rendering logic correctly handles all checkout scenarios.

The conditional logic properly prioritizes needsPaymentMethod to determine the checkout flow:

  • When false: Always renders FreeTrialButton (no payment collection)
  • When true: Renders appropriate payment method form based on paymentMethodSource

This addresses the free-trial-without-payment-method requirement and maintains backward compatibility for downgrades and immediate plan changes.

Optional: Add inline comments for complex conditional.

Consider adding brief comments explaining each branch to improve maintainability:

-      {!needsPaymentMethod ? (
+      {/* Free trials: no payment method required */}
+      {!needsPaymentMethod ? (
         <FreeTrialButton />
+      {/* Payment required: show appropriate form based on source */}
       ) : paymentMethodSource === 'existing' ? (
         <ExistingPaymentMethodForm paymentMethods={paymentMethods} />
       ) : (
         !__BUILD_DISABLE_RHC__ && paymentMethodSource === 'new' && <AddPaymentMethodForCheckout />
       )}
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 0a4d9ec and eb24790.

📒 Files selected for processing (1)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (12 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
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
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
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/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
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/ui/components/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 (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
  • useCheckoutContext (10-37)
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/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
packages/clerk-js/src/ui/styledSystem/types.ts (2)
  • PropsOfComponent (58-58)
  • ThemableCssProp (58-58)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-148)
⏰ 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). (4)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (4)

2-2: LGTM: Import updates are necessary and properly typed.

The added type imports are correctly used later in the file and follow TypeScript best practices for type-only imports.

Also applies to: 18-18


141-195: LGTM: Payment without payment method flow is correctly implemented.

The new payWithoutPaymentMethod mutation follows the established pattern and correctly calls confirmCheckout with an empty params object, enabling free trials without requiring payment method collection.


389-413: LGTM: New components follow best practices.

CheckoutSubmitButton and formProps are well-designed:

  • Proper TypeScript typing with PropsOfComponent and ThemableCssProp
  • Consistent use of theme tokens and localization
  • Appropriate spread operator usage for prop forwarding
  • Follows coding guidelines for UI components

415-492: Edge case confirmed as real but not a code defect.

The edge case (empty payment methods with RHC disabled + payment required) is theoretically possible but doesn't require frontend fixes:

  • Form submission handler extracts whatever value is in the form (line 169)
  • Backend validation is responsible for rejecting invalid/empty payment source IDs
  • This aligns with the minimal validation pattern in the component
  • RHC-disabled + zero payment methods is an extremely rare legacy scenario
  • Test coverage exists for related payment method scenarios

The updates to ExistingPaymentMethodForm correctly implement the needsPaymentMethod flag and properly handle both rendering paths (downgrades vs. immediate changes). No additional frontend safeguards are needed.

Comment on lines +354 to +368
const FreeTrialButton = withCardStateProvider(() => {
const { for: _for } = useCheckoutContext();
const { payWithoutPaymentMethod } = useCheckoutMutations();
const card = useCardState();

return (
<Form
onSubmit={payWithoutPaymentMethod}
sx={formProps}
>
<Card.Alert>{card.error}</Card.Alert>
<CheckoutSubmitButton />
</Form>
);
});
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 | 🟡 Minor

Remove unused destructured variable.

Line 355 destructures for: _for from the context but never uses it. This appears to be leftover from refactoring.

Apply this diff:

 const FreeTrialButton = withCardStateProvider(() => {
-  const { for: _for } = useCheckoutContext();
   const { payWithoutPaymentMethod } = useCheckoutMutations();
   const card = useCardState();
📝 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 FreeTrialButton = withCardStateProvider(() => {
const { for: _for } = useCheckoutContext();
const { payWithoutPaymentMethod } = useCheckoutMutations();
const card = useCardState();
return (
<Form
onSubmit={payWithoutPaymentMethod}
sx={formProps}
>
<Card.Alert>{card.error}</Card.Alert>
<CheckoutSubmitButton />
</Form>
);
});
const FreeTrialButton = withCardStateProvider(() => {
const { payWithoutPaymentMethod } = useCheckoutMutations();
const card = useCardState();
return (
<Form
onSubmit={payWithoutPaymentMethod}
sx={formProps}
>
<Card.Alert>{card.error}</Card.Alert>
<CheckoutSubmitButton />
</Form>
);
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx around lines
354 to 368, the destructured variable `for: _for` is unused; remove the `for:
_for` from the useCheckoutContext() destructure so the context is accessed
without extracting an unused binding, leaving the const as `const { } =
useCheckoutContext();` or simply `useCheckoutContext();` (prefer keeping any
needed hook call) and ensure no other references depend on `_for`.

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.

3 participants