Skip to content

Conversation

@panteliselef
Copy link
Member

@panteliselef panteliselef commented Aug 26, 2025

Description

Since FAPI now returns the payer information, we can infer the organization id during confirmation and stop requiring as a parameter. This results to improved DX and also eliminates the possibility of a wrong organization id being passed.

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

    • Billing (Beta): Checkout.confirm no longer requires an organization ID — it's inferred from the started checkout for a simpler flow.
    • Checkout now exposes a payer entity (user and organization info where available) across the checkout API and UI hooks, enabling richer checkout context.
  • Chores

    • Minor version bumps for @clerk/clerk-js, @clerk/shared, and @clerk/types.

@changeset-bot
Copy link

changeset-bot bot commented Aug 26, 2025

🦋 Changeset detected

Latest commit: 716c373

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/shared 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/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/vue Patch
@clerk/localizations Patch
@clerk/themes 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 Aug 26, 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 Aug 26, 2025 9:12pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 26, 2025

Walkthrough

This PR removes the orgId parameter from checkout.confirm(), infers organization from a new CommercePayer on the checkout, adds CommercePayer resources and types, updates CommerceCheckout construction and confirm path resolution, and adjusts billing module, hook defaults, and UI to call confirm() without orgId.

Changes

Cohort / File(s) Summary of changes
Changeset / Versions
\.changeset/proud-walls-travel.md
Notes minor version bumps and documents the public API change: checkout.confirm() no longer accepts orgId; it is inferred.
Types: commerce & json
packages/types/src/commerce.ts, packages/types/src/json.ts
Removes WithOptionalOrgType wrapper from ConfirmCheckoutParams; adds CommercePayerResource and CommercePayerJSON; adds payer to CommerceCheckoutResource and CommerceCheckoutJSON.
Core resource: CommerceCheckout
packages/clerk-js/src/core/resources/CommerceCheckout.ts
Removes orgId constructor parameter; adds payer: CommercePayerResource; confirm() no longer accepts orgId and resolves path from payer.organizationId or /me.
New core resource: CommercePayer
packages/clerk-js/src/core/resources/CommercePayer.ts
Adds CommercePayer class implementing CommercePayerResource with id, timestamps, imageUrl, optional user and organization fields, and JSON parsing.
Billing module
packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
startCheckout now constructs CommerceCheckout with a single JSON argument (orgId no longer passed to constructor).
UI & Hooks
packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx, packages/shared/src/react/hooks/useCheckout.ts
Removes useOrganization usage; calls confirm() without orgId; exposes checkout.payer in hook and sets default payer: null when absent.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor App
  participant Billing as Billing Module
  participant Checkout as CommerceCheckout
  participant API as Clerk API

  App->>Billing: startCheckout({ orgId })
  Billing-->>App: CommerceCheckout (contains payer with organizationId)
  note right of App: orgId captured in payer, not passed to confirm

  App->>Checkout: confirm(params)
  alt payer.organizationId present
    Checkout->>API: POST /organizations/{orgId}/billing/checkouts/{id}/confirm
  else no organizationId
    Checkout->>API: POST /me/billing/checkouts/{id}/confirm
  end
  API-->>Checkout: 200/response
  Checkout-->>App: Promise<void>
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

I thump with joy in dotted logs,
No orgId needed—fewer cogs!
A payer hops with tidy cheer,
Guides the path to far or near.
Types aligned, the checkout sings—🥕

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f7f8dff and 716c373.

⛔ Files ignored due to path filters (1)
  • .typedoc/__tests__/__snapshots__/file-structure.test.ts.snap is excluded by !**/*.snap
📒 Files selected for processing (1)
  • .changeset/proud-walls-travel.md (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/proud-walls-travel.md
⏰ 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). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/bill-1201-ga-improve-checkout-confirmation-js-api

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

Status, Documentation and Community

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

@panteliselef panteliselef requested review from a team and aeliox and removed request for a team and aeliox August 26, 2025 17:05
@pkg-pr-new
Copy link

pkg-pr-new bot commented Aug 26, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 716c373

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 (13)
.changeset/proud-walls-travel.md (3)

2-5: Sanity-check semver level vs. API surface change

If existing apps commonly call checkout.confirm({ orgId }), removing that parameter from the public TS type would be a source-incompatible change and should be a major bump. If the old shape is still accepted (ignored/deprecated) and the new zero-arg call is additive, a minor bump is fine. Please confirm which of the two applies and adjust the bump notes accordingly (and consider adding a brief deprecation note if backward-compatible).


9-19: Make the examples consistent and more precise

  • Use consistent casing for the root object (Clerk vs clerk) across “Before/After”. Pick the one that matches your docs (global Clerk or instance clerk) and stick to it.
  • Add colons after “After”/“Before”.
  • Clarify the comment to say that orgId is inferred (from payer), not just “implied”.

Proposed edits (assuming the global Clerk form is correct—adjust to clerk if that’s your canonical usage):

-After
+After:
 ```tsx
-const checkout = Clerk.billing.startCheckout({orgId})
-checkout.confirm() // orgId is always implied
+const checkout = Clerk.billing.startCheckout({ orgId });
+checkout.confirm(); // orgId is inferred from the checkout’s payer

-Before
+Before:

-const checkout = clerk.billing.startCheckout({orgId})
-checkout.confirm({orgId})
+const checkout = Clerk.billing.startCheckout({ orgId });
+checkout.confirm({ orgId });

If the instance form (`clerk`) is the canonical usage in your SDK docs, swap `Clerk` → `clerk` in both snippets.

---

`9-19`: **Add a short migration note to reduce churn**

Consider appending a “Migration” section to the changeset with one-liners for users skimming release notes.

Suggested addition:

```diff
+Migration:
+- Replace `checkout.confirm({ orgId })` with `checkout.confirm()`.
+- Ensure the `orgId` you pass to `startCheckout({ orgId })` matches the payer’s organization; `confirm()` now derives the resource from `checkout.payer`.
+- If you still call `confirm({ orgId })`, it will ${kept ? 'continue to work but is deprecated' : 'no longer type-check'}.

Please tune the last bullet to reflect the actual backward-compat story.

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

901-917: Align CommercePayerJSON with backend DTO or annotate divergence

There are notable differences vs backend JSON (see packages/backend/src/api/resources/JSON.ts):

  • instance_id exists and is required in backend but is missing here.
  • email is required in backend but optional here.
  • image_url is non-nullable in backend but nullable here.

If the runtime layer doesn’t rely on these fields, this is harmless; otherwise it risks drift. Prefer matching the backend DTO and relaxing at the resource layer if needed.

Apply this minimal, non-breaking alignment (keep looser nullability to avoid forced changes, but surface the field to avoid silent drift):

 export interface CommercePayerJSON extends ClerkResourceJSON {
   object: 'commerce_payer';
   id: string;
   created_at: number;
   updated_at: number;
   image_url: string | null;
 
   // User attributes
   user_id?: string;
-  email?: string;
+  email?: string;
   first_name?: string;
   last_name?: string;
 
   // Organization attributes
   organization_id?: string;
   organization_name?: string;
+  /**
+   * Backend emits instance_id; exposed for completeness, not used in clients.
+   */
+  instance_id?: string;
 }

If this divergence is intentional (public/SDK JSON vs backend-internal JSON), please add a short comment noting the contract.

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

1359-1410: ConfirmCheckoutParams is too permissive; enforce mutually exclusive modes

Each union member’s properties are optional, so {} is currently valid, and callers can accidentally mix modes (e.g., paymentToken + useTestCard). This weakens type-safety on a public API. Recommend an XOR style with required keys per mode.

Proposed stricter, backwards-compatible typing (disallows empty/mixed payloads):

-export type ConfirmCheckoutParams =
-  | {
-      /**
-       * @experimental ...
-       */
-      paymentSourceId?: string;
-    }
-  | {
-      /**
-       * @experimental ...
-       */
-      paymentToken?: string;
-      /**
-       * @experimental ...
-       */
-      gateway?: PaymentGateway;
-    }
-  | {
-      /**
-       * @experimental ...
-       */
-      gateway?: PaymentGateway;
-      /**
-       * @experimental ...
-       */
-      useTestCard?: boolean;
-    };
+export type ConfirmCheckoutParams =
+  | {
+      /**
+       * Use an existing payment source by id.
+       */
+      paymentSourceId: string;
+      paymentToken?: never;
+      gateway?: never;
+      useTestCard?: never;
+    }
+  | {
+      /**
+       * Use a new payment method via token from the specified gateway.
+       */
+      paymentToken: string;
+      gateway: PaymentGateway;
+      paymentSourceId?: never;
+      useTestCard?: never;
+    }
+  | {
+      /**
+       * Use a test card via the specified gateway.
+       */
+      gateway: PaymentGateway;
+      useTestCard: true;
+      paymentSourceId?: never;
+      paymentToken?: never;
+    };

If tightening types right now is risky for downstreams, at minimum add JSDoc warnings that exactly one mode must be provided.


1532-1631: CommercePayerResource shape looks good; confirm parity with JSON and consider future-proofing

The resource fields mirror CommercePayerJSON and use Date where appropriate. Two follow-ups:

  • Confirm the mapper handles optional email/imageUrl consistently and that organizationId/organizationName are only present for org payers.
  • Consider adding a small type discriminator (e.g., payerType: 'org' | 'user') at the resource level for ergonomics, derived from plan or presence of organizationId. This can be deferred.
packages/clerk-js/src/core/resources/CommerceCheckout.ts (4)

29-29: Clarify payer nullability and make confirm path resolution resilient

There’s an implicit assumption that payer is always present and non-null. However, related changes (e.g., UI hook defaulting payer to null) suggest payer may be absent at certain stages. Accessing this.payer.organizationId would then throw.

Two safe paths—pick one and align types across packages:

  • Option A (enforce invariant): Fail fast if data.payer is missing. Keeps current public shape intact.
  • Option B (nullable): Allow payer to be null and guard in confirm.

If you choose Option B, apply this localized refactor:

-  payer!: CommercePayerResource;
+  payer!: CommercePayerResource | null;
-    this.payer = new CommercePayer(data.payer);
+    this.payer = data.payer ? new CommercePayer(data.payer) : null;
-          path: this.payer.organizationId
+          path: this.payer?.organizationId
             ? `/organizations/${this.payer.organizationId}/commerce/checkouts/${this.id}/confirm`
             : `/me/commerce/checkouts/${this.id}/confirm`,

If you prefer Option A, add:

+    if (!data.payer) {
+      throw new Error('Checkout payload missing payer; cannot infer resource for confirmation.');
+    }
+    this.payer = new CommercePayer(data.payer);

I can follow up with a types audit to ensure CommerceCheckoutJSON['payer'] and CommerceCheckoutResource['payer'] match the chosen invariant.

Also applies to: 52-53, 63-65


63-66: Replace as any with precise typing and extract path builder for testability

  • Casting params to any weakens type safety against ConfirmCheckoutParams.
  • Building the confirm path inline makes it harder to unit-test and reuse.

Apply:

-          body: params as any,
+          body: params as ConfirmCheckoutParams,

Optionally extract a helper for path construction:

+  private getConfirmPath(): string {
+    const orgId = this.payer?.organizationId;
+    return orgId
+      ? `/organizations/${orgId}/commerce/checkouts/${this.id}/confirm`
+      : `/me/commerce/checkouts/${this.id}/confirm`;
+  }
-          path: this.payer?.organizationId
-            ? `/organizations/${this.payer.organizationId}/commerce/checkouts/${this.id}/confirm`
-            : `/me/commerce/checkouts/${this.id}/confirm`,
+          path: this.getConfirmPath(),

Bonus: consider retrying on 429 with respect to Retry-After when available.


57-60: Sync retry comments with implementation and consider 429

The comment says “retry up to 3 times” and lists 2s, 4s, 6s, 8s, which is 4 retries. The guard iterations >= 4 suggests 4 retries. Please reconcile the comment with behavior. Also consider including 429 handling with backoff since confirmation can be rate-limited.

Also applies to: 74-85


31-34: No outdated CommerceCheckout usages found; please add constructor JSDoc

I’ve verified that all existing call sites use the new single‐argument constructor and that there are no lingering orgId parameters:

  • Only usage of new CommerceCheckout(json) is in
    packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts:157
  • No occurrences of checkout.confirm({... orgId ...}) in .ts/.tsx files

Next, let’s document the constructor’s behavior. Here’s a suggested JSDoc snippet to add immediately above the constructor in
packages/clerk-js/src/core/resources/CommerceCheckout.ts:

   /**
+   * Instantiate a CommerceCheckout resource from its JSON representation.
+   *
+   * @param data - Raw `CommerceCheckoutJSON` payload.
+   *
+   * @remarks
+   * The organization ID is automatically inferred from `payer.organizationId`.  
+   * If no organization is found on the payer, the resource will default to `/me`.
+   */
   constructor(data: CommerceCheckoutJSON) {
     super();
     this.fromJSON(data);
   }

Let me know if you’d like any tweaks to the wording or additional examples.

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

19-22: Constructor should accept nullable JSON to match fromJSON and callers

fromJSON already handles null, but the constructor enforces a non-null JSON. Allow null for symmetry and safer calls from resources that may receive incomplete payloads.

Apply:

-  constructor(data: CommercePayerJSON) {
+  constructor(data: CommercePayerJSON | null) {
     super();
     this.fromJSON(data);
   }

If the API guarantees payer is always present, alternatively keep as-is and add a runtime assert in callers. Otherwise, prefer this change.


24-40: Defensive parsing for timestamps and JSDoc for public fields

  • If created_at/updated_at can ever be absent, unixEpochToDate(undefined) may yield an invalid Date. Either assert presence or make these fields nullable and guard.
  • Add JSDoc on the class and fields—this is a public API surface and guidelines require JSDoc.

Apply defensiveness if needed:

-    this.createdAt = unixEpochToDate(data.created_at);
-    this.updatedAt = unixEpochToDate(data.updated_at);
+    this.createdAt = data.created_at ? unixEpochToDate(data.created_at) : new Date(0);
+    this.updatedAt = data.updated_at ? unixEpochToDate(data.updated_at) : new Date(0);

I can also draft JSDoc (purpose, fields, and examples) if helpful.


7-17: Consider marking immutable identity fields as readonly (if objects aren’t rehydrated)

If instances aren’t re-used via fromJSON after construction, id, createdAt, and updatedAt can be readonly to reflect immutability. If rehydration is common in your resource layer, skip this.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f871573 and f7f8dff.

📒 Files selected for processing (8)
  • .changeset/proud-walls-travel.md (1 hunks)
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (1 hunks)
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts (3 hunks)
  • packages/clerk-js/src/core/resources/CommercePayer.ts (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (2 hunks)
  • packages/shared/src/react/hooks/useCheckout.ts (1 hunks)
  • packages/types/src/commerce.ts (3 hunks)
  • packages/types/src/json.ts (1 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/types/src/json.ts
  • packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/resources/CommercePayer.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/types/src/commerce.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/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/resources/CommercePayer.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/types/src/commerce.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/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/resources/CommercePayer.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/types/src/commerce.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/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/resources/CommercePayer.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/types/src/commerce.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/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/resources/CommercePayer.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/types/src/commerce.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/core/modules/commerce/CommerceBilling.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/core/resources/CommercePayer.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/types/src/commerce.ts
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/proud-walls-travel.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 (2)
packages/types/src/json.ts (1)
packages/backend/src/api/resources/JSON.ts (2)
  • CommercePayerJSON (787-799)
  • ClerkResourceJSON (78-87)
packages/types/src/commerce.ts (1)
packages/types/src/resource.ts (1)
  • ClerkResource (8-21)
⏰ 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). (6)
  • GitHub Check: pr-title-lint
  • 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 (8)
packages/types/src/json.ts (1)

890-891: CommerceCheckout.payer Mapping Verified; Please Confirm API Coverage

I’ve validated that the client-side handling of the new required payer field is wired up correctly, but the backend API still needs a manual check:

• In packages/clerk-js/src/core/resources/CommerceCheckout.ts, the constructor calls

this.payer = new CommercePayer(data.payer);

ensuring data.payer is consumed with a non-null assertion.
• All instantiations of new CommerceCheckout(json) in packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts pass a CommerceCheckoutJSON payload that must include payer.
• The JSON type definition in packages/types/src/json.ts declares

export interface CommerceCheckoutJSON {
  
  payer: CommercePayerJSON;
}

making the property required in the shared types.

Action required: the repo does not contain the backend serializers, so please manually verify that both the start and confirm commerce_checkout endpoints always include a non-null payer field in their responses. If any rollout window might omit payer, consider reverting to an optional property or gating the change via versioned DTOs to avoid breaking consumers.

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

1521-1530: Adding payer to CommerceCheckoutResource: LGTM

Non-null payer: CommercePayerResource here keeps runtime shape consistent with the JSON change. Ensure the constructor/resource mapper always instantiates payer.

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

116-116: Expose payer in the no-checkout fallback: LGTM

Including payer: null keeps the public shape stable. Matches CheckoutProperties after adding payer to the resource.

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

1-1: Import path change: OK

Switching to @clerk/shared/react for useCheckout is consistent with shared hook exposure. No issues spotted.


152-152: Confirm now omits orgId: ensure return type alignment and path resolution

Calling confirm(params) without augmenting orgId looks correct with payer-based inference. However, the call expects { data, error } while CommerceCheckoutResource.confirm’s type is Promise<CommerceCheckoutResource>. If useCheckout overrides this to return a result envelope, ensure the public typing in __experimental_UseCheckoutReturn reflects that to avoid confusion for integrators. Also, confirm that the underlying resource resolves the correct confirm path from checkout.payer.

packages/clerk-js/src/core/modules/commerce/CommerceBilling.ts (1)

157-157: CommerceCheckout confirm path derivation is correct

I’ve verified that:

  • The CommercePayer constructor maps data.organization_id to this.organizationId (see line 37 in CommercePayer.ts).
  • The CommerceCheckout confirm() method checks this.payer.organizationId and uses
    • /organizations/${this.payer.organizationId}/… when present
    • /me/… otherwise
      (lines 63–65 in CommerceCheckout.ts).

No changes are needed here.

packages/clerk-js/src/core/resources/CommerceCheckout.ts (1)

6-6: LGTM: Type-only import and concrete resource import

The import type { CommercePayerResource } and concrete CommercePayer import cleanly separate types vs values and align with the new inference model.

Also applies to: 14-14

packages/clerk-js/src/core/resources/CommercePayer.ts (1)

1-6: Imports and base class usage look correct

Type-only import for shapes and BaseResource extension align with package conventions.

'@clerk/types': minor
---

[Billing Beta] `checkout.confirm()` now infers the resource id resulting an less repetition and improved DX.
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix grammar and clarify what is inferred

Minor copy edit and clarity: “resulting an less repetition” → “resulting in less repetition”; explicitly say “resource ID (orgId)” and “from the checkout’s payer”.

Apply:

-[Billing Beta] `checkout.confirm()` now infers the resource id resulting an less repetition and improved DX.
+[Billing Beta] `checkout.confirm()` now infers the resource ID (orgId) from the checkout’s payer, resulting in less repetition and improved DX.
📝 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
[Billing Beta] `checkout.confirm()` now infers the resource id resulting an less repetition and improved DX.
[Billing Beta] `checkout.confirm()` now infers the resource ID (orgId) from the checkout’s payer, resulting in less repetition and improved DX.
🤖 Prompt for AI Agents
In .changeset/proud-walls-travel.md around line 7, fix the grammar and clarify
the inference description: change “resulting an less repetition” to “resulting
in less repetition” and rephrase to explicitly state “resource ID (orgId)
inferred from the checkout’s payer” so the sentence reads clearly that
checkout.confirm() now infers the resource ID (orgId) from the checkout’s payer,
resulting in less repetition and improved DX.

@panteliselef panteliselef self-assigned this Aug 26, 2025
Co-authored-by: Robert Soriano <sorianorobertc@gmail.com>
@panteliselef panteliselef enabled auto-merge (squash) August 26, 2025 21:11
@panteliselef panteliselef merged commit 377f67b into main Aug 27, 2025
63 of 64 checks passed
@panteliselef panteliselef deleted the elef/bill-1201-ga-improve-checkout-confirmation-js-api branch August 27, 2025 21:44
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