Skip to content

Conversation

@mauricioabreu
Copy link
Contributor

@mauricioabreu mauricioabreu commented Oct 20, 2025

Description

It's flag-based

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

    • Configurable setting to require (or not) a payment method for free trial subscriptions.
    • Checkout UI updated to conditionally show payment-method sections and an alternate "Start free trial" path when payment info isn't required.
    • Checkout completion text now reflects whether a payment method is involved when a free trial ends.
  • Tests

    • Expanded coverage for free-trial flows across multiple billing configurations.
  • Chores

    • Added changelog/changeset entry and package version bumps.

@changeset-bot
Copy link

changeset-bot bot commented Oct 20, 2025

🦋 Changeset detected

Latest commit: a2b55d9

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 20, 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 24, 2025 2:06pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 20, 2025

Walkthrough

Adds a configurable flag controlling whether free trials require a payment method, updates types and commerce settings model to include the flag, adjusts checkout UI and completion messaging to honor the flag, and expands fixtures and tests to cover trial flows with and without payment requirements.

Changes

Cohort / File(s) Summary
Type Definitions & Changeset
packages/types/src/commerceSettings.ts, .changeset/bumpy-glasses-eat.md
Added free_trial_requires_payment_method: boolean to CommerceSettingsJSON and freeTrialRequiresPaymentMethod: boolean to CommerceSettingsResource; created changeset bump for packages.
Commerce Settings Model
packages/clerk-js/src/core/resources/CommerceSettings.ts
Added billing.freeTrialRequiresPaymentMethod field, populated from data.billing.free_trial_requires_payment_method ?? true in fromJSON, and serialized as free_trial_requires_payment_method in snapshots.
Checkout UI Components
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx, packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
Consumed environment commerce settings to gate payment UI: compute isFreeTrial, showTabs, needsPaymentMethod; conditionally render Tabs, ExistingPaymentMethodForm, FreeTrialButton, and updated completion text logic to consider freeTrialRequiresPaymentMethod. Added payWithoutPaymentMethod mutation wiring and replaced inline submit button with centralized CheckoutSubmitButton.
Test Fixtures & Tests
packages/clerk-js/src/test/fixture-helpers.ts, packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx
Extended withBilling fixture to accept options including freeTrialRequiresPaymentMethod (defaults true) and updated fixtures; added extensive tests for free-trial flows covering UI variations, hidden inputs, and button states for both payment-required and not-required scenarios.
Bundle Config
packages/clerk-js/bundlewatch.config.json
Increased maxSize for ./dist/checkout*.js entry from 8.77KB to 10KB.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CheckoutForm
    participant Environment
    participant MutationService

    User->>CheckoutForm: Open checkout / select plan
    CheckoutForm->>Environment: read commerceSettings.billing.freeTrialRequiresPaymentMethod
    Environment-->>CheckoutForm: flag (true/false)

    alt flag = true
        CheckoutForm->>CheckoutForm: Show payment tabs & existing/new payment UI
        User->>CheckoutForm: Provide/select payment method
        CheckoutForm->>MutationService: submit with payment_method_id
    else flag = false
        CheckoutForm->>CheckoutForm: Hide payment method UI, show FreeTrialButton
        User->>CheckoutForm: Click Start free trial
        CheckoutForm->>MutationService: payWithoutPaymentMethod mutation
    end

    MutationService-->>CheckoutForm: success
    CheckoutForm-->>User: show confirmation (CheckoutComplete)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Poem

🐰 I hopped into code with a twitch of my nose,

A flag for free trials — how quietly it grows.
Tabs appear, tabs hide, a button for mirth,
Start the trial now, no payment on earth.
A carrot for testers, and joy in the merge.

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 PR title "feat(clerk-js,types): Make payment method optional for free trials" directly and accurately describes the main change across the entire changeset. The modifications introduce a new freeTrialRequiresPaymentMethod flag that gates payment method requirements during checkout, allowing payment methods to be optional for free trials. The title is concise, specific, and uses the conventional semantic commit format without unnecessary noise or vague terminology. It clearly identifies the affected packages and the primary feature being implemented, making it easy for teammates to understand the core change from the title alone.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a29eff7 and a2b55d9.

📒 Files selected for processing (1)
  • packages/clerk-js/bundlewatch.config.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/clerk-js/bundlewatch.config.json
⏰ 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). (29)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

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 2d44e17 to 273cba7 Compare October 23, 2025 03:50
@mauricioabreu mauricioabreu changed the title feat(clerk-js): Make requiring a credit card a toggle for free trials feat(clerk-js,types): Make payment method optional for free trials Oct 23, 2025
@mauricioabreu mauricioabreu marked this pull request as ready for review October 23, 2025 11:09
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

Caution

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

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

428-467: Omit hidden payment method input when payment methods aren't shown.

The form unconditionally extracts and sends the hidden payment_method_id input (line 168-172), but when showPaymentMethods is false (lines 462-466), selectedPaymentMethod?.id is undefined, resulting in an empty string being passed to confirmCheckout({ paymentSourceId: "" }).

This violates the documented API constraint: "Only one of paymentSourceId, paymentToken, or useTestCard should be provided" (billing.ts). An empty string still counts as "provided" and may cause unexpected backend behavior.

Fix: Conditionally render the hidden input only when showPaymentMethods is true, or validate and filter empty strings before passing to confirmCheckout.

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

414-417: Duplicate logic - see comment on lines 226-232.

This calculation duplicates the showPaymentMethods logic from CheckoutFormElementsInternal. Please refactor to use the shared hook suggested in the earlier comment.

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

485-501: Consider a more specific element descriptor.

The component uses descriptors.formButtonPrimary, which is generic. For consistency with the codebase patterns and to enable specific theming of checkout buttons, consider using a dedicated descriptor like descriptors.checkoutSubscribeButton or similar.

Example:

-    <Button
-      elementDescriptor={descriptors.formButtonPrimary}
-      onClick={subscribeWithoutPaymentMethod}
+    <Button
+      elementDescriptor={descriptors.checkoutSubscribeButton}
+      onClick={subscribeWithoutPaymentMethod}

Note: This would require adding the new descriptor to the descriptors object. As per coding guidelines

Based on coding guidelines for packages/clerk-js/src/ui/**/*.{ts,tsx}.

📜 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 25f54f6 and 273cba7.

📒 Files selected for processing (4)
  • .changeset/bumpy-glasses-eat.md (1 hunks)
  • packages/clerk-js/src/core/resources/CommerceSettings.ts (3 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (7 hunks)
  • packages/types/src/commerceSettings.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{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/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/types/src/commerceSettings.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/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/types/src/commerceSettings.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/types/src/commerceSettings.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/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/types/src/commerceSettings.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/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/types/src/commerceSettings.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/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/types/src/commerceSettings.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/bumpy-glasses-eat.md
packages/clerk-js/src/ui/**/*.{ts,tsx}

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

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

Files:

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

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

**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components: UserProfile, NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
**/*.tsx

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

**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1)
packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
🔇 Additional comments (8)
packages/types/src/commerceSettings.ts (2)

8-8: LGTM! Type definition is backward-compatible.

The optional field in the JSON interface allows backward compatibility with existing data while the implementation provides a sensible default.


23-28: LGTM! Well-documented type definition.

The JSDoc clearly explains the flag's purpose and default behavior. The required field in the Resource interface is appropriate since the implementation guarantees it's always present via the default value.

packages/clerk-js/src/core/resources/CommerceSettings.ts (3)

11-11: LGTM! Conservative default is appropriate.

Defaulting to true (requiring payment methods) is the safer choice for billing flows, preventing accidental free access without payment information.


33-33: LGTM! Proper handling of missing field.

The nullish coalescing operator correctly handles backward compatibility when the field is absent from the JSON response.


46-46: LGTM! Serialization is complete.

The field is properly included in the snapshot output with the correct naming convention.

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

15-15: LGTM! Import addition is necessary.

The useEnvironment hook is required to access the new billing flag.


183-189: LGTM! New mutation properly integrated.

The subscribeWithoutPaymentMethod function correctly calls confirmCheckout with empty parameters, allowing subscription without payment method information.


267-280: LGTM! Conditional rendering logic is correct.

The three mutually exclusive rendering paths properly handle:

  1. Existing payment method selection
  2. New payment method addition
  3. Standalone subscription without payment method

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from 273cba7 to 5fb8034 Compare October 23, 2025 20:23
@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 23, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: a2b55d9

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/hooks/useShowPaymentMethods.ts (1)

14-30: Hook logic is correct and readable.

The implementation properly handles the conditions for showing payment methods. The redundant isImmediatePlanChange check on line 26 (already checked on line 21) makes the return statement more explicit and self-documenting, which aids readability.

If you prefer a more concise implementation, you could remove the redundant check on line 26:

-  return (
-    isImmediatePlanChange &&
-    (totals.totalDueNow.amount > 0 ||
-      (!!freeTrialEndsAt && environment.commerceSettings.billing.freeTrialRequiresPaymentMethod))
-  );
+  return (
+    totals.totalDueNow.amount > 0 ||
+    (!!freeTrialEndsAt && environment.commerceSettings.billing.freeTrialRequiresPaymentMethod)
+  );

However, the current explicit form is perfectly acceptable and may be preferred for clarity.

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

373-398: Minor optimization opportunity: duplicate hook call.

The useShowPaymentMethods hook is called both in CheckoutFormElementsInternal (line 226) and again here in ExistingPaymentMethodForm (line 398). While this works correctly and hooks are cheap, you could optimize by passing showPaymentMethods as a prop to avoid duplicate computation.

 const ExistingPaymentMethodForm = withCardStateProvider(
-  ({ paymentMethods }: { paymentMethods: BillingPaymentMethodResource[] }) => {
+  ({ paymentMethods, showPaymentMethods }: { paymentMethods: BillingPaymentMethodResource[]; showPaymentMethods: boolean }) => {
     const submitLabel = useSubmitLabel();
     const { checkout } = useCheckout();
     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 = useShowPaymentMethods();

Then update the call on line 262:

-      {showPaymentMethods && paymentMethodSource === 'existing' && (
-        <ExistingPaymentMethodForm paymentMethods={paymentMethods} />
+      {showPaymentMethods && paymentMethodSource === 'existing' && (
+        <ExistingPaymentMethodForm paymentMethods={paymentMethods} showPaymentMethods={showPaymentMethods} />
📜 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 273cba7 and 5fb8034.

📒 Files selected for processing (6)
  • .changeset/bumpy-glasses-eat.md (1 hunks)
  • packages/clerk-js/src/core/resources/CommerceSettings.ts (3 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (8 hunks)
  • packages/clerk-js/src/ui/hooks/index.ts (1 hunks)
  • packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts (1 hunks)
  • packages/types/src/commerceSettings.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/bumpy-glasses-eat.md
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts
  • packages/clerk-js/src/ui/hooks/index.ts
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts
  • packages/clerk-js/src/ui/hooks/index.ts
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts
  • packages/clerk-js/src/ui/hooks/index.ts
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts
  • packages/clerk-js/src/ui/hooks/index.ts
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts
  • packages/clerk-js/src/ui/hooks/index.ts
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts
  • packages/clerk-js/src/ui/hooks/index.ts
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.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/hooks/useShowPaymentMethods.ts
  • packages/clerk-js/src/ui/hooks/index.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
packages/**/index.{js,ts}

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

Use tree-shaking friendly exports

Files:

  • packages/clerk-js/src/ui/hooks/index.ts
**/index.ts

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

Use index.ts files for clean imports but avoid deep barrel exports

Avoid barrel files (index.ts re-exports) as they can cause circular dependencies

Files:

  • packages/clerk-js/src/ui/hooks/index.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
**/*.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 (5)
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/hooks/useShowPaymentMethods.ts (1)
  • useShowPaymentMethods (14-30)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-147)
packages/clerk-js/src/ui/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
⏰ 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). (3)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (13)
packages/types/src/commerceSettings.ts (2)

8-8: LGTM! Proper backward-compatible JSON field.

The optional field ensures backward compatibility with existing API responses that may not include this field.


23-28: LGTM! Well-documented required field with sensible default.

The JSDoc clearly explains the purpose and default behavior, maintaining backward compatibility by defaulting to true (existing behavior).

packages/clerk-js/src/core/resources/CommerceSettings.ts (3)

11-11: LGTM! Proper default initialization.

The default value of true ensures existing behavior is maintained, requiring payment methods for free trials unless explicitly configured otherwise.


33-33: LGTM! Correct nullish coalescing with proper default.

The nullish coalescing operator (??) properly handles missing or null values from the API, ensuring the default behavior is preserved.


46-46: LGTM! Proper serialization to JSON format.

Correctly maps the camelCase property back to snake_case for JSON serialization, maintaining consistency with the API contract.

packages/clerk-js/src/ui/hooks/index.ts (1)

19-19: LGTM! Proper public API export.

The hook is correctly exported following the established pattern, making it available for consumption by other components.

packages/clerk-js/src/ui/hooks/useShowPaymentMethods.ts (1)

5-13: LGTM! Comprehensive JSDoc documentation.

The documentation clearly explains the hook's purpose and the conditions under which payment methods are shown, following the coding guidelines for public APIs.

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

2-2: LGTM! Proper type-only imports.

Using import type for type-only imports follows TypeScript best practices and coding guidelines, enabling better tree-shaking.


16-16: LGTM! Correct hook import.

The hook is properly imported from the public API surface via the hooks barrel export.


219-219: LGTM! Clean refactoring.

Correctly removes properties now handled by the useShowPaymentMethods hook, reducing duplication and improving code organization.


226-270: LGTM! Correct conditional rendering logic.

The conditional rendering properly uses showPaymentMethods to control UI visibility:

  • Shows payment method forms when needed (lines 240-267)
  • Shows standalone subscribe button for free trials without payment requirements (line 270)

This correctly implements the feature requirements.


466-482: LGTM! Well-implemented standalone subscribe button.

The component correctly:

  • Wraps with withCardStateProvider for state management
  • Uses the subscribeWithoutPaymentMethod mutation
  • Handles loading states
  • Applies proper styling and localization

This enables users to subscribe to free trials without providing payment methods when the flag allows it.


184-190: Code is correct as-is—no backend verification needed.

The subscribeWithoutPaymentMethod function correctly calls confirmCheckout({}) with an empty object. The ConfirmCheckoutParams type definition explicitly allows this since all three union members contain only optional properties. This is the intended behavior for free trial subscriptions that don't require payment methods, as confirmed by existing tests like "Start free trial" button scenarios. TypeScript's type system already validates that an empty object is a valid ConfirmCheckoutParams, so the code is properly typed and safe.

@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch 2 times, most recently from cd13d00 to 6006406 Compare October 23, 2025 20:33
@mauricioabreu mauricioabreu force-pushed the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch from 6006406 to 0d3c55a Compare October 23, 2025 23:00
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)

223-229: Duplication still present despite past review.

A previous review comment flagged this duplicated logic (also at lines 461-464 in ExistingPaymentMethodForm) and suggested extracting to a useShowPaymentMethods hook. The comment was marked as "Addressed in commit 5fb8034", but the duplication remains in the current code.

Please extract this logic into a shared custom hook:

// In a shared hooks file
const useShowPaymentMethods = () => {
  const { checkout } = useCheckout();
  const environment = useEnvironment();
  const { isImmediatePlanChange, totals, freeTrialEndsAt } = checkout;
  
  return (
    isImmediatePlanChange &&
    (totals.totalDueNow.amount > 0 ||
      (!!freeTrialEndsAt && environment.commerceSettings.billing.freeTrialRequiresPaymentMethod))
  );
};

Then use in both locations:

-  const showPaymentMethods =
-    isImmediatePlanChange &&
-    (totals.totalDueNow.amount > 0 ||
-      (!!freeTrialEndsAt && environment.commerceSettings.billing.freeTrialRequiresPaymentMethod));
+  const showPaymentMethods = useShowPaymentMethods();

461-464: Duplicate logic - see comment on lines 223-229.

This calculation duplicates the showPaymentMethods logic from lines 223-229. Extract to a shared useShowPaymentMethods hook as suggested in the earlier comment.

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

358-407: Add element descriptor for theming support.

A previous review comment suggested adding a unique elementDescriptor for this button to enable custom styling. Per coding guidelines, element descriptors should be used in UI components to enable consistent theming via appearance.elements.

Apply this diff:

 const FreeTrialButton = withCardStateProvider(() => {
   const { for: _for, onSubscriptionComplete } = useCheckoutContext();
   const submitLabel = useSubmitLabel();
   const card = useCardState();
   const { checkout } = useCheckout();

   const handleFreeTrialStart = async () => {
     card.setLoading();
     card.setError(undefined);

     try {
       // For free trials without payment method requirement, we can confirm without payment details
       const { data, error } = await checkout.confirm({});

       if (error) {
         handleError(error, [], card.setError);
       } else if (data) {
         onSubscriptionComplete?.();
       }
     } catch (error) {
       handleError(error, [], card.setError);
     } finally {
       card.setIdle();
     }
   };

   return (
     <Form
+      elementDescriptor={descriptors.checkoutFreeTrialForm}
       sx={t => ({
         display: 'flex',
         flexDirection: 'column',
         rowGap: t.space.$4,
       })}
     >
       <Card.Alert>{card.error}</Card.Alert>
       <Button
+        elementDescriptor={descriptors.checkoutFreeTrialButton}
         type='button'
         colorScheme='primary'
         size='sm'
         textVariant={'buttonLarge'}
         sx={{
           width: '100%',
         }}
         isLoading={card.isLoading}
         localizationKey={submitLabel}
         onClick={handleFreeTrialStart}
       />
     </Form>
   );
 });

You'll also need to add the corresponding descriptor keys to your descriptors object.

📜 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 6006406 and 0d3c55a.

📒 Files selected for processing (5)
  • .changeset/bumpy-glasses-eat.md (1 hunks)
  • packages/clerk-js/src/core/resources/CommerceSettings.ts (3 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx (3 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (6 hunks)
  • packages/types/src/commerceSettings.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{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/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/types/src/commerceSettings.ts
  • 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/core/resources/CommerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutComplete.tsx
  • packages/types/src/commerceSettings.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/bumpy-glasses-eat.md
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
**/*.{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
**/*.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
🧬 Code graph analysis (2)
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/elements/contexts/index.tsx (2)
  • withCardStateProvider (72-81)
  • useCardState (42-70)
packages/clerk-js/src/ui/contexts/components/Checkout.ts (1)
  • useCheckoutContext (10-37)
packages/shared/src/react/hooks/useCheckout.ts (1)
  • useCheckout (70-147)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (64-86)
⏰ 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)
.changeset/bumpy-glasses-eat.md (1)

1-6: LGTM!

The changeset correctly documents the feature with appropriate minor version bumps and a clear changelog entry.

packages/types/src/commerceSettings.ts (2)

8-8: LGTM!

The optional free_trial_requires_payment_method field in the JSON interface correctly represents the wire format with snake_case naming.


23-28: LGTM!

The freeTrialRequiresPaymentMethod field is properly documented with JSDoc describing its purpose and default value. The required field is appropriate for the runtime resource model.

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

8-8: LGTM!

The useEnvironment hook is correctly imported and used to access commerce settings.

Also applies to: 165-165


434-443: LGTM!

The updated conditional logic correctly gates payment method display based on the new freeTrialRequiresPaymentMethod setting. The logic consistently applies to both title and description, ensuring payment method information only appears when either there's an amount due or it's a free trial requiring a payment method.

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

15-15: LGTM!

The useEnvironment hook is correctly imported and used to access commerce settings.

Also applies to: 217-217


264-275: LGTM!

The conditional rendering logic correctly shows payment method UIs when required and falls back to the FreeTrialButton when payment methods are not needed.

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

46-46: LGTM!

The serialization correctly converts freeTrialRequiresPaymentMethod to free_trial_requires_payment_method for the JSON snapshot.


11-11: Default value true is intentional and documented in JSDoc.

The implementation is consistent: line 11 sets the default to true in the constructor, and line 33 uses ?? true as the fallback when the API doesn't provide the field. The JSDoc documentation in packages/types/src/commerceSettings.ts (lines 25-27) explicitly states @default true with the rationale: "When false, users can start free trials without providing payment methods."

This conservative default (requiring payment methods for free trials) appears intentional for safety. However, the codebase does not contain explicit confirmation that this aligns with backend API contract expectations or product requirements. Please confirm with your backend team or product that this default behavior is correct.

Copy link
Member

@panteliselef panteliselef left a comment

Choose a reason for hiding this comment

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

@mauricioabreu can you update the description with an image of the new UI ?

@panteliselef
Copy link
Member

@mauricioabreu take a look at my changes in #7065, one test was failing, plus I did some minor improvements.

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 0d3c55a and 1d2ec0b.

📒 Files selected for processing (4)
  • .changeset/pretty-garlics-sing.md (1 hunks)
  • packages/clerk-js/src/test/fixture-helpers.ts (1 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)
🚧 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 (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/clerk-js/src/test/fixture-helpers.ts
  • 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/__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/__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/__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/__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/__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
**/*.{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
**/*.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
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/pretty-garlics-sing.md
🧬 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)
🪛 LanguageTool
.changeset/pretty-garlics-sing.md

[grammar] ~1-~1: Hier könnte ein Fehler sein.
Context: --- ---

(QB_NEW_DE)

⏰ 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 (6)
packages/clerk-js/src/ui/components/Checkout/__tests__/Checkout.test.tsx (5)

934-937: LGTM - Minor consistency improvement.

Extracting the button to a variable before asserting is a reasonable consistency improvement, though the inline assertion was also acceptable.


939-1041: LGTM - Comprehensive test coverage for free trial in Add payment method tab.

This test properly verifies that the "Start free trial" button appears in the Add payment method tab when a free trial is available. The fixture setup is thorough and follows established patterns.


1043-1131: LGTM - Good coverage of required payment method scenario.

This test effectively validates the behavior when a free trial requires a payment method but none exists. The fixture configuration with freeTrialRequiresPaymentMethod: true properly exercises this code path.


1133-1227: LGTM - Excellent validation of optional payment method flow.

This test thoroughly validates that when freeTrialRequiresPaymentMethod is false, the payment method UI is completely hidden, including both visible controls and hidden inputs. This is critical for ensuring users can start free trials without payment information when configured.


1229-1337: LGTM - Critical edge case coverage.

This test is particularly valuable as it validates that when payment methods are not required for free trials, the UI correctly hides payment method information even when stored methods exist. This prevents user confusion and ensures the flag behavior is respected regardless of payment method state.

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

365-383: LGTM - Well-structured fixture helper enhancement.

The updated withBilling helper properly supports the new freeTrialRequiresPaymentMethod configuration with a sensible default of true. The object parameter pattern with explicit types and defaults makes the API flexible and maintainable while preserving backward compatibility.

@mauricioabreu mauricioabreu self-assigned this Oct 24, 2025
@mauricioabreu mauricioabreu deleted the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch October 24, 2025 19:57
@mauricioabreu mauricioabreu restored the mauricio-antunes/bill-1298-make-requiring-a-credit-card-a-toggle-for-free-trials branch October 24, 2025 20:37
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.

4 participants