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
    • Users can start free trials without entering payment details; checkout adapts when payment is not required.
  • Updates
    • Checkout UI and submit flows streamlined with clearer buttons and form behavior for free-trial vs. paid flows.
    • Increased bundle size threshold for checkout assets.
  • Tests
    • Expanded tests covering free-trial and checkout scenarios to ensure correct UI behavior.

@changeset-bot
Copy link

changeset-bot bot commented Oct 24, 2025

🦋 Changeset detected

Latest commit: eb4f109

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 27, 2025 8:38pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 24, 2025

Walkthrough

Adds a boolean flag needsPaymentMethod across types, resources, hooks, UI, and tests; introduces a payWithoutPaymentMethod mutation, a standardized CheckoutSubmitButton and FreeTrialButton, updates fixtures and tests for free-trial flows, and bumps bundlewatch size and package versions.

Changes

Cohort / File(s) Summary
Types & JSON
packages/types/src/billing.ts, packages/types/src/json.ts
Added needsPaymentMethod: boolean / needs_payment_method: boolean to billing checkout types/JSON.
Resources
packages/clerk-js/src/core/resources/BillingCheckout.ts
Added public needsPaymentMethod property and hydrate it from data.needs_payment_method in fromJSON.
Hooks / Initial State
packages/shared/src/react/hooks/useCheckout.ts
Added needsPaymentMethod: null to the initial empty checkout state so the property is present in the exported checkout surface.
Checkout UI & Mutations
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx, packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
Replaced previous total-based checks with needsPaymentMethod; added payWithoutPaymentMethod mutation, FreeTrialButton, CheckoutSubmitButton, shared form styling, and updated rendering logic to show free-trial flow when needsPaymentMethod is false.
Tests & Fixtures
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx, packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts, packages/clerk-js/src/test/fixture-helpers.ts
Updated fixtures to include needsPaymentMethod; added and adjusted tests for free-trial and payment flows; made withBilling configurable with options.
Bundlewatch Config
packages/clerk-js/bundlewatch.config.json
Increased allowed size for checkout*.js artifact (~8.77KB → 10KB).
Changeset
.changeset/bumpy-glasses-eat.md
Documented minor package bumps for @clerk/clerk-js and @clerk/types and the feature: "Make payment method optional for free trials".

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CheckoutForm
    participant API
    participant CheckoutComplete

    User->>CheckoutForm: Open checkout
    Note over CheckoutForm: read needsPaymentMethod
    alt needsPaymentMethod = false
        CheckoutForm->>User: Render FreeTrialButton (form)
        User->>CheckoutForm: Submit free-trial
        CheckoutForm->>API: payWithoutPaymentMethod() -> confirmCheckout({})
    else needsPaymentMethod = true
        CheckoutForm->>User: Render payment forms / existing methods
        User->>CheckoutForm: Choose/enter payment and submit
        CheckoutForm->>API: confirmCheckout(paymentMethodId)
    end
    API->>CheckoutComplete: confirmation
    CheckoutComplete->>User: render success (trial or paid)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Verify consistent replacement of previous total/trial checks with needsPaymentMethod across UI and logic.
  • Inspect payWithoutPaymentMethod for correct event handling, validation, and side effects.
  • Confirm resource JSON mapping and initial empty-state typing for needsPaymentMethod.
  • Review updated tests and fixture usages for comprehensive coverage.

Poem

🐰 I found a flag and gave a cheer,
No card required to start the year.
A button hops, a trial takes flight,
Forms align, the flow feels light.
Code nibbled — checkout's just right.

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" accurately reflects the main objective and changes throughout the changeset. The core feature introduces a new needsPaymentMethod boolean field across multiple packages (clerk-js, types, clerk-js/src/core/resources) to conditionally control whether payment methods are required for free-trial flows. The UI components are refactored to render either a FreeTrialButton or payment method forms based on this flag, and comprehensive tests are added to verify the new behavior. The title is concise, specific, and clearly communicates the primary change without being vague or misleading.
✨ 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

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

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.

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)

357-357: Remove unused variable.

Line 357 destructures for: _for from the context but never uses it. This was flagged in a previous review and should be removed.

Apply this diff:

 const FreeTrialButton = withCardStateProvider(() => {
-  const { for: _for } = useCheckoutContext();
   const { payWithoutPaymentMethod } = useCheckoutMutations();
   const card = useCardState();
📜 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 8095cff and 6eb7163.

📒 Files selected for processing (8)
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts (1 hunks)
  • packages/clerk-js/src/test/fixture-helpers.ts (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (11 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (6 hunks)
  • packages/types/src/billing.ts (1 hunks)
  • packages/types/src/commerceSettings.ts (1 hunks)
  • packages/types/src/json.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/types/src/json.ts
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/billing.ts
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • 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/types/src/billing.ts
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • 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/types/src/billing.ts
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • 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/types/src/billing.ts
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • 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/types/src/billing.ts
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
  • 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/types/src/billing.ts
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • 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/core/modules/checkout/__tests__/manager.test.ts
  • 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/core/modules/checkout/__tests__/manager.test.ts
  • 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/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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
**/*.{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
**/*.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
🧬 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/clerk-js/src/ui/styledSystem/types.ts (2)
  • PropsOfComponent (58-58)
  • ThemableCssProp (58-58)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-147)
⏰ 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/test/fixture-helpers.ts (1)

365-380: LGTM!

The enhanced withBilling helper now supports configurable billing flags for more flexible test scenarios. The defaults maintain backward compatibility.

packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts (1)

24-24: LGTM!

The mock correctly includes the new needsPaymentMethod field to align with the updated BillingCheckoutResource interface.

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

786-789: LGTM!

The needsPaymentMethod field is properly documented and cleanly extends the BillingCheckoutResource interface.

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

943-1344: LGTM! Comprehensive test coverage for needsPaymentMethod.

The new tests thoroughly validate the checkout flow across multiple scenarios:

  • Free trials with/without payment method requirements
  • Presence/absence of stored payment methods
  • Correct rendering of UI elements (tabs, buttons, hidden inputs)

The test suite properly exercises the conditional logic introduced by needsPaymentMethod.

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

176-179: LGTM! New mutation for checkout without payment method.

The payWithoutPaymentMethod function correctly handles free trial submissions that don't require payment details.

Also applies to: 193-193


222-222: LGTM! Rendering logic correctly handles needsPaymentMethod.

The updated conditional rendering properly branches on needsPaymentMethod:

  • When false: renders FreeTrialButton (no payment collection)
  • When true: renders payment method forms based on source

This aligns with test expectations and the feature requirements.

Also applies to: 229-229, 264-273


391-409: LGTM! CheckoutSubmitButton standardizes submit buttons.

The new component provides a consistent, reusable submit button for checkout forms with proper loading state and localization.


418-420: LGTM! ExistingPaymentMethodForm correctly uses needsPaymentMethod.

The form logic properly distinguishes between immediate changes (free trials) and downgrades using needsPaymentMethod, ensuring the correct UI elements render for each scenario.

Also applies to: 442-442, 490-490

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from 6eb7163 to 85a4414 Compare October 27, 2025 01:01
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

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

357-357: Remove unused destructured variable.

for: _for is destructured but never used. This was flagged in previous reviews.

Apply this diff:

 const FreeTrialButton = withCardStateProvider(() => {
-  const { for: _for } = useCheckoutContext();
   const { payWithoutPaymentMethod } = useCheckoutMutations();
   const card = useCardState();
🧹 Nitpick comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

418-418: Clean up unused totalDueNow parameter.

The type annotation includes totalDueNow: BillingMoneyAmount but the component never destructures or uses it. Either remove it from the type and call site (line 268), or document why it's retained.

Apply this diff to remove it:

 const ExistingPaymentMethodForm = withCardStateProvider(
-  ({ paymentMethods }: { totalDueNow: BillingMoneyAmount; paymentMethods: BillingPaymentMethodResource[] }) => {
+  ({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {

And at the call site (line 268):

         <ExistingPaymentMethodForm
           paymentMethods={paymentMethods}
-          totalDueNow={totals.totalDueNow}
         />
📜 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 6eb7163 and 85a4414.

📒 Files selected for processing (8)
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts (1 hunks)
  • packages/clerk-js/src/test/fixture-helpers.ts (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (11 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (6 hunks)
  • packages/types/src/billing.ts (1 hunks)
  • packages/types/src/commerceSettings.ts (1 hunks)
  • packages/types/src/json.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/types/src/json.ts
  • packages/clerk-js/src/core/modules/checkout/tests/manager.test.ts
  • packages/types/src/commerceSettings.ts
  • packages/types/src/billing.ts
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/test/fixture-helpers.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/clerk-js/src/test/fixture-helpers.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}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/test/fixture-helpers.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/clerk-js/src/test/fixture-helpers.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/clerk-js/src/test/fixture-helpers.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/clerk-js/src/test/fixture-helpers.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
🧬 Code graph analysis (3)
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/clerk-js/src/ui/styledSystem/types.ts (2)
  • PropsOfComponent (58-58)
  • ThemableCssProp (58-58)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-147)
packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (1)
packages/clerk-js/src/ui/elements/LineItems.tsx (1)
  • LineItems (289-294)
⏰ 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: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (1)

164-164: LGTM! Cleaner logic with needsPaymentMethod flag.

The introduction of needsPaymentMethod centralizes the decision about whether to show payment method UI vs. subscription start details. This is more explicit than deriving intent from totals.totalDueNow.amount > 0 or freeTrialEndsAt !== null.

Also applies to: 332-337, 389-392, 433-450

packages/clerk-js/src/test/fixture-helpers.ts (1)

365-380: LGTM! Test helper now configurable.

The updated signature makes it easy to test different billing configurations without duplicating fixture helpers.

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

943-1046: LGTM! Comprehensive test coverage for needsPaymentMethod.

The new tests cover all key scenarios:

  • Free trials with required PM and existing PMs (tabs shown)
  • Free trials with required PM and no PMs (no tabs, straight to add PM)
  • Free trials without required PM (no PM UI, hidden input not rendered)
  • Free trials without required PM but with stored PMs (still no PM UI)

These cases ensure the UI correctly respects the needsPaymentMethod flag.

Also applies to: 1048-1137, 1139-1234, 1236-1344

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

264-273: LGTM! Rendering logic correctly branches on needsPaymentMethod.

The refactored rendering ensures:

  • Free trials without required PM render FreeTrialButton (no PM collection)
  • When PM is required, the UI respects paymentMethodSource to show existing PMs or add-new flow
  • CheckoutSubmitButton and formProps provide consistent styling across forms

This aligns with the test expectations and past review fixes.

Also applies to: 356-370, 391-409

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from 85a4414 to a75c973 Compare October 27, 2025 01:05
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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

244-249: Localize “aria-label” for SegmentedControl.Root

Hard-coded 'Payment method source' violates the localization rule. Use a localized string via useLocalizations.

Example:

-            <SegmentedControl.Root
-              aria-label='Payment method source'
+            {/* obtain `t` from useLocalizations() */}
+            <SegmentedControl.Root
+              aria-label={t(localizationKeys('billing.checkout.paymentMethodSourceAriaLabel'))}

If SegmentControl supports a localizationKey prop for labels, prefer that. As per coding guidelines.

packages/shared/src/react/hooks/useCheckout.ts (1)

103-119: Add planPeriodStart to the null-initialized fallback object

CheckoutProperties is derived from BillingCheckoutResource, which includes planPeriodStart as an optional property. The fallback object at lines 106–118 omits planPeriodStart despite it being part of the type signature. Consumers like CheckoutComplete.tsx destructure and reference planPeriodStart, making this a type inconsistency.

Add to the fallback:

       totals: null,
       isImmediatePlanChange: null,
       planPeriod: null,
       plan: null,
       paymentMethod: null,
+      planPeriodStart: null,
       freeTrialEndsAt: null,
       payer: null,
       needsPaymentMethod: null,
♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

356-370: Remove unused _for from useCheckoutContext destructure

This unused binding will fail ESLint (no-unused-vars). Remove it.

-const FreeTrialButton = withCardStateProvider(() => {
-  const { for: _for } = useCheckoutContext();
+const FreeTrialButton = withCardStateProvider(() => {
   const { payWithoutPaymentMethod } = useCheckoutMutations();
   const card = useCardState();
🧹 Nitpick comments (5)
packages/clerk-js/src/test/fixture-helpers.ts (1)

365-380: Add explicit return type and extract options type for withBilling

Good change. To align with TS and DRY, give withBilling an explicit return type and extract the options type alias.

Apply:

-  const withBilling = ({
-    userEnabled = true,
-    userHasPaidPlans = true,
-    organizationEnabled = true,
-    organizationHasPaidPlans = true,
-  }: {
-    userEnabled?: boolean;
-    userHasPaidPlans?: boolean;
-    organizationEnabled?: boolean;
-    organizationHasPaidPlans?: boolean;
-  } = {}) => {
+  type WithBillingOptions = {
+    userEnabled?: boolean;
+    userHasPaidPlans?: boolean;
+    organizationEnabled?: boolean;
+    organizationHasPaidPlans?: boolean;
+  };
+  const withBilling = ({
+    userEnabled = true,
+    userHasPaidPlans = true,
+    organizationEnabled = true,
+    organizationHasPaidPlans = true,
+  }: WithBillingOptions = {}): void => {
     os.user.enabled = userEnabled;
     os.user.has_paid_plans = userHasPaidPlans;
     os.organization.enabled = organizationEnabled;
     os.organization.has_paid_plans = organizationHasPaidPlans;
   };
packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (1)

439-449: Localize placeholder instead of hard-coded dash

The fallback '–' is hard-coded. Per UI guidelines, use a localization key for “not available/unknown”.

Consider:

-                    : '–'
+                    : localizationKeys('billing.checkout.placeholder__notAvailable')
@@
-                    : '–'
+                    : localizationKeys('billing.checkout.placeholder__notAvailable')

If no existing key, add one to the l10n bundle. As per coding guidelines.

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

267-271: Drop unused totalDueNow prop from ExistingPaymentMethodForm

Prop is passed but never used; remove from prop type and call sites to reduce coupling.

-        <ExistingPaymentMethodForm
-          paymentMethods={paymentMethods}
-          totalDueNow={totals.totalDueNow}
-        />
+        <ExistingPaymentMethodForm paymentMethods={paymentMethods} />

And adjust signature:

-const ExistingPaymentMethodForm = withCardStateProvider(
-  ({ paymentMethods }: { totalDueNow: BillingMoneyAmount; paymentMethods: BillingPaymentMethodResource[] }) => {
+const ExistingPaymentMethodForm = withCardStateProvider(
+  ({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {

Also applies to: 418-421

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

1048-1137: Clarify test name to match assertions

The test asserts no tabs/buttons for adding a PM and presence of “Start free trial”, which contradicts the current title.

Rename to reflect behavior, e.g., “shows free-trial submit when PM is required but no stored methods (RHC shows add-PM form)”.


469-475: Stabilize date assertions against locale/TZ drift

Asserting 'August 19, 2025' can be flaky across locales/timezones. Prefer deriving the formatted string via the same formatter or match via regex for month/day/year.

Example:

const expected = new Intl.DateTimeFormat('en-US', { month:'long', day:'numeric', year:'numeric' }).format(new Date('2025-08-19'));
expect(getByText(expected)).toBeVisible();

Also applies to: 564-568

📜 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 85a4414 and a75c973.

📒 Files selected for processing (8)
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts (1 hunks)
  • packages/clerk-js/src/test/fixture-helpers.ts (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (4 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (11 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (6 hunks)
  • packages/shared/src/react/hooks/useCheckout.ts (1 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/clerk-js/src/core/modules/checkout/tests/manager.test.ts
  • packages/types/src/json.ts
  • packages/types/src/billing.ts
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/test/fixture-helpers.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • 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/test/fixture-helpers.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • 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/test/fixture-helpers.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • 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/test/fixture-helpers.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • 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/test/fixture-helpers.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/test/fixture-helpers.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.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/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • 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/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • 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/CheckoutComplete.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/CheckoutComplete.tsx (1)
packages/clerk-js/src/ui/elements/LineItems.tsx (1)
  • LineItems (289-294)
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/contexts/components/Plans.tsx (1)
  • usePaymentMethods (32-40)
packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-148)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (3)
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/test/utils.ts (1)
  • waitFor (73-73)
⏰ 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 (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (1)

331-337: Title/description branching reads well

Switching to needsPaymentMethod for success text selection matches the new API and keeps free-trial precedence via freeTrialEndsAt. LGTM.

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

264-273: Render flow now correctly gates on needsPaymentMethod

Branching first on needsPaymentMethod prevents accidental PM-collection UI for free trials. Good fix.

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from a75c973 to 0a78990 Compare October 27, 2025 01:20
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

♻️ Duplicate comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)

356-370: Remove unused destructured variable.

Line 357 destructures for: _for from useCheckoutContext() but never uses it. This was already flagged in a previous review.

Apply this diff:

 const FreeTrialButton = withCardStateProvider(() => {
-  const { for: _for } = useCheckoutContext();
   const { payWithoutPaymentMethod } = useCheckoutMutations();
   const card = useCardState();
📜 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 a75c973 and 0a78990.

📒 Files selected for processing (9)
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts (1 hunks)
  • 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 (4 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (11 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (6 hunks)
  • packages/shared/src/react/hooks/useCheckout.ts (1 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 (5)
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/types/src/billing.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • packages/types/src/json.ts
  • packages/clerk-js/src/ui/components/Checkout/tests/Checkout.test.tsx
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{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/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/core/resources/BillingCheckout.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/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/core/resources/BillingCheckout.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/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/core/resources/BillingCheckout.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/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
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/core/modules/checkout/__tests__/manager.test.ts
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/core/modules/checkout/__tests__/manager.test.ts
**/*.{js,ts,tsx,jsx}

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

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

Files:

  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
**/__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/core/modules/checkout/__tests__/manager.test.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • 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/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.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
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
🧬 Code graph analysis (2)
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/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/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (1)
packages/clerk-js/src/ui/elements/LineItems.tsx (1)
  • LineItems (289-294)
⏰ 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: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
packages/clerk-js/src/core/resources/BillingCheckout.ts (1)

33-33: LGTM! Clean addition of the needsPaymentMethod field.

The boolean field declaration and JSON mapping follow the established patterns in this resource class.

Also applies to: 57-57

packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts (1)

24-24: LGTM! Appropriate test fixture update.

The default value of true for needsPaymentMethod maintains backward compatibility with existing test scenarios.

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

164-164: LGTM! Clean refactor to explicit payment method requirement flag.

The shift from inferring payment requirements via totals.totalDueNow.amount > 0 to using the explicit needsPaymentMethod flag improves clarity and moves the business logic decision to the backend where it belongs. The UI now correctly distinguishes between payment-required flows and free-trial/subscription-only flows across title, description, and line items.

Also applies to: 334-336, 389-391, 433-448

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

18-18: LGTM! Appropriate type imports.

The new imports PropsOfComponent and ThemableCssProp are correctly used for the new CheckoutSubmitButton component and formProps styling object.


176-179: LGTM! Clean mutation for payment-free checkout.

The payWithoutPaymentMethod mutation correctly handles free-trial scenarios where no payment method is required, calling confirmCheckout({}) with empty parameters.

Also applies to: 193-193


222-222: LGTM! Rendering logic correctly handles payment-optional flows.

The refactored conditional rendering properly prioritizes needsPaymentMethod:

  • When false: renders FreeTrialButton (no payment collection)
  • When true: renders appropriate payment forms based on paymentMethodSource and RHC feature flag

This addresses the issues raised in previous reviews.

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


391-409: LGTM! Excellent refactor for button and styling consistency.

The extracted CheckoutSubmitButton component and shared formProps styling object reduce duplication and ensure consistent form layout and submit button behavior across payment flows.

Also applies to: 411-415


420-420: LGTM! Consistent integration of needsPaymentMethod flag.

The ExistingPaymentMethodForm correctly uses needsPaymentMethod to determine whether to display the payment method selector UI (showPaymentMethods) or just maintain a hidden input for deferred payment scenarios (downgrades). The form styling and submit button updates align with the broader refactor.

Also applies to: 442-442, 447-447, 490-490

paymentMethods: BillingPaymentMethodResource[];
}) => {
const submitLabel = useSubmitLabel();
({ paymentMethods }: { totalDueNow: BillingMoneyAmount; paymentMethods: BillingPaymentMethodResource[] }) => {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion | 🟠 Major

Fix type annotation mismatch.

Line 418's type annotation declares totalDueNow: BillingMoneyAmount in the props interface, but totalDueNow is never destructured or used in the component. Line 269 passes this prop, but it serves no purpose.

Apply this diff to remove the unused prop from the type:

 const ExistingPaymentMethodForm = withCardStateProvider(
-  ({ paymentMethods }: { totalDueNow: BillingMoneyAmount; paymentMethods: BillingPaymentMethodResource[] }) => {
+  ({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {
     const { checkout } = useCheckout();

And remove it from the call site:

       ) : paymentMethodSource === 'existing' ? (
         <ExistingPaymentMethodForm
           paymentMethods={paymentMethods}
-          totalDueNow={totals.totalDueNow}
         />
📝 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
({ paymentMethods }: { totalDueNow: BillingMoneyAmount; paymentMethods: BillingPaymentMethodResource[] }) => {
({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {
const { checkout } = useCheckout();
Suggested change
({ paymentMethods }: { totalDueNow: BillingMoneyAmount; paymentMethods: BillingPaymentMethodResource[] }) => {
) : paymentMethodSource === 'existing' ? (
<ExistingPaymentMethodForm
paymentMethods={paymentMethods}
/>
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx around line
418, the props type for the inline function incorrectly includes totalDueNow:
BillingMoneyAmount even though totalDueNow is not destructured or used; remove
totalDueNow from the type annotation so the parameter becomes ({ paymentMethods
}: { paymentMethods: BillingPaymentMethodResource[] }). Also update the call
site (around line 269) to stop passing totalDueNow into this component/handler
so the prop is no longer provided.

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from 0a78990 to eb4f109 Compare October 27, 2025 20:37
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

♻️ Duplicate comments (2)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2)

356-370: Unused destructured variable should be removed.

Line 357 destructures for: _for from useCheckoutContext() but never uses it. This is leftover from refactoring.

Apply this diff:

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

418-418: Unused prop type should be removed.

The type annotation declares totalDueNow: BillingMoneyAmount but this prop is never destructured or used in the component. Line 269 passes this prop unnecessarily.

Apply this diff to remove the unused prop from the type:

 const ExistingPaymentMethodForm = withCardStateProvider(
-  ({ paymentMethods }: { totalDueNow: BillingMoneyAmount; paymentMethods: BillingPaymentMethodResource[] }) => {
+  ({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {
     const { checkout } = useCheckout();

And remove it from the call site:

       ) : paymentMethodSource === 'existing' ? (
         <ExistingPaymentMethodForm
           paymentMethods={paymentMethods}
-          totalDueNow={totals.totalDueNow}
         />
🧹 Nitpick comments (1)
packages/types/src/json.ts (1)

819-819: Add JSDoc documentation for the new public field.

The new needs_payment_method field is part of the public API but lacks documentation. While the parent interface has an @experimental JSDoc tag, individual fields in similar interfaces often include inline comments explaining their purpose.

Consider adding a JSDoc comment:

   free_trial_ends_at: number | null;
   payer: BillingPayerJSON;
+  /**
+   * Indicates whether a payment method is required for this checkout.
+   */
   needs_payment_method: boolean;
 }
📜 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 0a78990 and eb4f109.

📒 Files selected for processing (9)
  • packages/clerk-js/src/core/modules/checkout/__tests__/manager.test.ts (1 hunks)
  • 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 (4 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (11 hunks)
  • packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (6 hunks)
  • packages/shared/src/react/hooks/useCheckout.ts (1 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 (4)
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/test/fixture-helpers.ts
  • packages/clerk-js/src/core/modules/checkout/tests/manager.test.ts
  • packages/clerk-js/src/core/resources/BillingCheckout.ts
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{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/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/types/src/billing.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/types/src/json.ts
  • 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/types/src/billing.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/types/src/json.ts
  • 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/types/src/billing.ts
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/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/types/src/billing.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/types/src/json.ts
  • 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/types/src/billing.ts
**/*.{js,ts,tsx,jsx}

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

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

Files:

  • packages/types/src/json.ts
  • 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/types/src/billing.ts
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/clerk-js-ui.mdc)

packages/clerk-js/src/ui/**/*.{ts,tsx}: Element descriptors should always be camelCase
Use element descriptors in UI components to enable consistent theming and styling via appearance.elements
Element descriptors should generate unique, stable CSS classes for theming
Element descriptors should handle state classes (e.g., cl-loading, cl-active, cl-error, cl-open) automatically based on component state
Do not render hard-coded values; all user-facing strings must be localized using provided localization methods
Use the useLocalizations hook and localizationKeys utility for all text and error messages
Use the styled system (sx prop, theme tokens, responsive values) for custom component styling
Use useCardState for card-level state, useFormState for form-level state, and useLoadingStatus for loading states
Always use handleError utility for API errors and use translateError for localized error messages
Use useFormControl for form field state, implement proper validation, and handle loading and error states in forms
Use localization keys for all form labels and placeholders
Use element descriptors for consistent styling and follow the theme token system
Use the Card and FormContainer patterns for consistent UI structure

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • 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/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • 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/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 (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/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/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). (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 (17)
packages/types/src/billing.ts (1)

786-789: LGTM!

The field is properly documented with JSDoc and follows TypeScript naming conventions. The type aligns with the JSON layer and the documentation clearly explains its purpose.

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

164-164: LGTM!

The destructuring of needsPaymentMethod from checkout extends the public data surface appropriately.


332-336: Success title logic correctly handles three states.

The conditional properly differentiates between free trial, payment successful, and subscription successful states with appropriate fallback logic.


389-391: Description logic appropriately simplified to binary choice.

The description correctly uses needsPaymentMethod to distinguish between payment and subscription flows without needing to check freeTrialEndsAt.


433-449: LineItems logic handles both payment method and subscription start cases.

The conditional correctly shows payment method details when needed and subscription start date otherwise, with proper fallbacks for missing data.

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

176-179: LGTM!

The new payWithoutPaymentMethod mutation correctly prevents default form submission and calls confirmCheckout with an empty object for free-trial flows that don't require payment methods.


189-194: Mutation properly exported for external use.

The payWithoutPaymentMethod function is correctly added to the hook's return value, enabling components like FreeTrialButton to trigger checkout without payment method collection.


391-409: LGTM!

The new CheckoutSubmitButton component appropriately standardizes submit button rendering across checkout forms with proper loading state and localization.


411-415: LGTM!

The formProps styling object provides consistent form layout across checkout forms with appropriate gap and flex properties.


222-222: LGTM!

Destructuring needsPaymentMethod from checkout properly extends the checkout data surface for conditional rendering logic.


264-273: Rendering logic correctly implements free-trial flow.

The conditional properly handles the three states:

  1. No payment method needed → FreeTrialButton (no collection UI)
  2. Payment method needed with existing source → ExistingPaymentMethodForm
  3. Payment method needed with new source → AddPaymentMethodForCheckout (when RHC enabled)

This addresses the critical issues from previous reviews.

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

938-941: LGTM!

Capturing the payButton variable enables proper assertion of the Pay button's presence in payment-required flows.


943-1046: LGTM!

Test correctly verifies that the "Start free trial" button appears in the Add payment method tab for free-trial scenarios where payment methods are required.


1048-1137: LGTM!

Test properly validates the scenario where no payment methods exist but one is required for a free trial - showing the payment method prompt without tabs.


1139-1234: LGTM!

Test correctly verifies that when needsPaymentMethod is false, the UI hides payment method controls, tabs, and the hidden payment_method_id input, even for free trials.


1236-1345: LGTM!

Test appropriately validates that when needsPaymentMethod is false, payment method UI remains hidden even when stored payment methods exist, ensuring no hidden input or payment method display.


548-548: Comprehensive test coverage for needsPaymentMethod flag.

The test suite properly exercises all combinations of needsPaymentMethod with various checkout states (free trials, immediate plan changes, downgrades) and payment method availability.

Also applies to: 640-640, 753-753, 893-893, 1020-1020, 1110-1110, 1201-1201, 1306-1306, 1438-1438

@mauricioabreu mauricioabreu self-assigned this Oct 28, 2025
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