Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Sep 3, 2025

Description

Issue

Currently, when users perform actions like confirming checkouts or canceling subscriptions, the UI doesn't automatically reflect these changes. Users need to manually refresh or navigate away and back to see updated data, leading to a poor user experience.

Solution

The proposed solution automatically revalidates data when relevant mutation occur, and deduplicates event listeners to avoid multiple parallel revalidation requests.

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
    • Subscription data now auto-updates after checkout confirmation and subscription item cancellation.
    • useSubscription hook now also returns isLoading, isFetching, and revalidate.
    • Introduced a throttled event mechanism to deduplicate concurrent revalidations.
  • Performance
    • Reduced redundant network requests via shared, throttled event listeners.
    • Disabled revalidation on window focus for subscriptions.
  • Chores
    • Internal plumbing to propagate resource action events across packages.

Copy link

changeset-bot bot commented Sep 3, 2025

⚠️ No Changeset found

Latest commit: f174b51

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

This PR includes no changesets

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

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

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

Copy link

vercel bot commented Sep 3, 2025

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

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 3, 2025 8:18pm

Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Walkthrough

Adds a new internal event channel resource:action across types and event bus, exposes the public event bus via a Clerk getter, emits events from checkout confirm and subscription item cancel, forwards listeners in IsomorphicClerk, introduces a throttled React event hook, refactors useSubscription to revalidate on these events, and removes subscriptions revalidation from Plans.

Changes

Cohort / File(s) Summary
Event typing and constants
packages/types/src/clerk.ts, packages/shared/src/clerkEventBus.ts
Adds ClerkEventPayload['resource:action'] with values 'checkout.confirm'
Clerk core: event bus exposure
packages/clerk-js/src/core/clerk.ts
Adds public getter __internal_eventBus returning #publicEventBus.
Resource emissions
packages/clerk-js/src/core/resources/CommerceCheckout.ts, packages/clerk-js/src/core/resources/CommerceSubscription.ts
CommerceCheckout.confirm made async, awaits retry result, then emits 'resource:action'='checkout.confirm'. CommerceSubscriptionItem.cancel emits 'resource:action'='subscriptionItem.cancel' post-DELETE.
Isomorphic listener forwarding
packages/react/src/isomorphicClerk.ts
hydrateClerkJS forwards existing 'resource:action' listeners from internal bus to IsomorphicClerk via this.on(..., { notify: true }).
React hooks: throttled events and subscription
packages/shared/src/react/hooks/useThrottledEvent.tsx, packages/shared/src/react/hooks/useSubscription.tsx
Adds useThrottledEvent: shared listener registry for 'resource:action' with ref-counted cleanup. Refactors useSubscription to key-based SWR, adds throttled revalidation on defined events, returns { data, error, isLoading, isFetching, revalidate }, disables revalidateOnFocus.
UI adjustments
packages/clerk-js/src/ui/contexts/components/Plans.tsx
Removes revalidate from useSubscription destructure; stops calling revalidateSubscriptions; updates deps accordingly.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as UI / Components
  participant Checkout as CommerceCheckout.confirm
  participant Clerk as Clerk.__internal_eventBus
  participant Iso as IsomorphicClerk
  participant Hook as useThrottledEvent listener
  participant Sub as useSubscription (SWR)
  participant API as clerk.billing.getSubscription

  User->>UI: Confirm checkout
  UI->>Checkout: confirm(params)
  Checkout->>Checkout: await retry(...)
  Checkout-->>Clerk: emit('resource:action', 'checkout.confirm')
  Note right of Clerk: New event channel
  Clerk-->>Iso: forward listener notification
  Iso-->>Hook: notify 'checkout.confirm'
  Hook->>Sub: trigger revalidate (throttled by key)
  Sub->>API: fetch subscription
  API-->>Sub: data
  Sub-->>UI: updated subscription state
Loading
sequenceDiagram
  autonumber
  participant UI as UI / Components
  participant Item as CommerceSubscriptionItem.cancel
  participant Clerk as Clerk.__internal_eventBus
  participant Iso as IsomorphicClerk
  participant Hook as useThrottledEvent listener
  participant Sub as useSubscription (SWR)

  UI->>Item: cancel()
  Item->>Item: DELETE → json
  Item-->>Clerk: emit('resource:action', 'subscriptionItem.cancel')
  Clerk-->>Iso: forward listener notification
  Iso-->>Hook: notify 'subscriptionItem.cancel'
  Hook->>Sub: revalidate (deduped)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

A rabbit taps the eventful ground,
“resource:action!” echoes round.
Checkout chirps, subscriptions chime,
hooks revalidate in perfect time.
Throttled hops avoid the stampede—
fresh data blooms from every feed.
I twitch, approve: proceed, proceed! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/bill-1236-auto-revalidate-hooks-on-mutations

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

Status, Documentation and Community

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

Copy link

pkg-pr-new bot commented Sep 3, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: f174b51

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

🧹 Nitpick comments (14)
packages/clerk-js/src/core/clerk.ts (1)

242-244: Type the internal getter and document intent

Add an explicit return type and a brief JSDoc noting this is internal-only. This keeps the public surface typed while signaling non-API status.

-  get __internal_eventBus() {
-    return this.#publicEventBus;
-  }
+  /**
+   * INTERNAL: exposed for cross-package wiring (not a supported public API).
+   * Do not rely on this outside Clerk-owned packages.
+   */
+  get __internal_eventBus(): ReturnType<typeof createClerkEventBus> {
+    return this.#publicEventBus;
+  }
packages/types/src/clerk.ts (1)

152-153: Centralize resource action literals into a named type

Defining a reusable alias improves discoverability and future extension (add actions in one place).

 export type ClerkEventPayload = {
   status: ClerkStatus;
-  'resource:action': 'checkout.confirm' | 'subscriptionItem.cancel';
+  'resource:action': ClerkResourceAction;
 };

Add near the other top-level type aliases (outside this hunk):

export type ClerkResourceAction = 'checkout.confirm' | 'subscriptionItem.cancel';
packages/clerk-js/src/core/resources/CommerceSubscription.ts (1)

120-121: Guard the internal bus access; add explicit return type (optional)

Avoid a rare NPE if BaseResource.clerk isn’t populated, and consider annotating the method’s return type.

-    CommerceSubscription.clerk.__internal_eventBus.emit('resource:action', 'subscriptionItem.cancel');
+    CommerceSubscription.clerk?.__internal_eventBus?.emit('resource:action', 'subscriptionItem.cancel');

Outside this hunk (optional):

public async cancel(params: CancelSubscriptionParams): Promise<DeletedObject> { ... }
packages/react/src/isomorphicClerk.ts (1)

568-571: Fix comment and use the event constant

Use the shared constant to avoid typos; correct the comment reference.

-    this.#eventBus.internal.retrieveListeners('resource:action')?.forEach(listener => {
-      // Since clerkjs exists it will call `this.clerkjs.on('status', listener)`
-      this.on('resource:action', listener, { notify: true });
-    });
+    this.#eventBus.internal.retrieveListeners(clerkEvents.ResourceAction)?.forEach(listener => {
+      // Since clerkjs exists it will call `this.clerkjs.on('resource:action', listener)`
+      this.on(clerkEvents.ResourceAction, listener, { notify: true });
+    });
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)

129-133: Optional: batch the cache invalidations to avoid interleaved re-renders.

Not critical, but batching avoids multiple state transitions when these resolve at slightly different times.

-  const revalidateAll = useCallback(() => {
-    // Revalidate the plans
-    void revalidatePlans();
-    void revalidateStatements();
-    void revalidatePaymentSources();
-  }, [revalidatePlans, revalidateStatements, revalidatePaymentSources]);
+  const revalidateAll = useCallback(async () => {
+    // Invalidate caches together
+    await Promise.all([revalidatePlans(), revalidateStatements(), revalidatePaymentSources()]);
+  }, [revalidatePlans, revalidateStatements, revalidatePaymentSources]);
packages/clerk-js/src/core/resources/CommerceCheckout.ts (1)

60-86: Comment vs behavior mismatch; avoid any in request body.

  • The retry comments (“up to 3 times”, “2s, 4s, 6s, 8s”) don’t match the config (cap at 2s, iterations check >= 4). Align the comment to the actual behavior or adjust the config.
  • Prefer a precise cast over any.
-    // Retry confirmation in case of a 500 error
-    // This will retry up to 3 times with an increasing delay
-    // It retries at 2s, 4s, 6s and 8s
+    // Retry on server errors or specific 409s.
+    // Retries up to 4 attempts with ~2s capped delay between attempts.
...
-          body: params as any,
+          body: params as ConfirmCheckoutParams,
packages/shared/src/react/hooks/useThrottledEvent.tsx (4)

18-36: Narrow the clerk param to the minimal surface.

Depending on a hook’s return type (useClerkInstanceContext) leaks an internal detail. Use a small interface to express what you need.

-import type { useClerkInstanceContext } from '../contexts';
+type ClerkLike = {
+  on: (event: 'resource:action', handler: (payload: ClerkEventPayload['resource:action']) => void) => void;
+  off: (event: 'resource:action', handler: (payload: ClerkEventPayload['resource:action']) => void) => void;
+};
...
-  clerk: ReturnType<typeof useClerkInstanceContext>;
+  clerk: ClerkLike;

68-97: Stale handler risk across shared keys.

When multiple components share uniqueKey, the first registrant’s handler is retained. If another component with the same key updates onEvent/events, its changes won’t be reflected until the first unmounts. Consider referencing a mutable ref for the callback to avoid stale closures.

-import { useEffect } from 'react';
+import { useEffect, useRef } from 'react';
...
+  const onEventRef = useRef(onEvent);
+  onEventRef.current = onEvent;
+
   if (existingEntry) {
     // Increment reference count for existing event listener
     existingEntry.refCount++;
   } else {
...
-      const handler = (payload: ClerkEventPayload['resource:action']) => {
-        if (events.includes(payload)) {
-          onEvent(payload);
-        }
-      };
+      const handler = (payload: ClerkEventPayload['resource:action']) => {
+        // Use latest callback without re-binding the listener.
+        if (events.includes(payload)) {
+          onEventRef.current(payload);
+        }
+      };

84-90: Handle Clerk instance swaps (SSR/hydration/HMR).

If the clerk instance changes while other references keep the listener alive, the registry continues using the old instance. Track the instance and rebind when it changes.

 type ThrottledEventRegistry = {
   refCount: number;
   handler: (payload: ClerkEventPayload['resource:action']) => void;
   cleanup: () => void;
+  clerk: unknown;
 };
 ...
-      // Register the event listener
+      // Register the event listener
       on('resource:action', handler);
 ...
       throttledEventRegistry.set(uniqueKey, {
         refCount: 1,
         handler,
         cleanup,
+        clerk,
       });
     }
 
     // Cleanup function
     return () => {
       if (!uniqueKey) return;
 
       const entry = throttledEventRegistry.get(uniqueKey);
       if (entry) {
+        // If Clerk instance changed, rebind to the new one for the next registrant
+        if (entry.clerk !== clerk && entry.refCount > 0) {
+          entry.cleanup();
+          const on = clerk.on.bind(clerk as any);
+          const off = clerk.off.bind(clerk as any);
+          on('resource:action', entry.handler);
+          entry.cleanup = () => off('resource:action', entry.handler);
+          entry.clerk = clerk;
+        }
         entry.refCount--;

Also applies to: 99-115


79-82: Micro: precompute membership for events.

If events grows, a Set avoids repeated linear scans. Minor impact here.

-      const handler = (payload: ClerkEventPayload['resource:action']) => {
-        if (events.includes(payload)) {
+      const eventsSet = new Set(events);
+      const handler = (payload: ClerkEventPayload['resource:action']) => {
+        if (eventsSet.has(payload)) {
           onEvent(payload);
         }
       };
packages/shared/src/react/hooks/useSubscription.tsx (4)

58-63: Minor: avoid param shadowing to improve readability

Rename the fetcher param so it doesn’t shadow the outer key binding.

-  const swr = useSWR(key, key => clerk.billing.getSubscription(key.args), {
+  const swr = useSWR(key, swrKey => clerk.billing.getSubscription(swrKey.args), {
     dedupingInterval: 1_000 * 60,
     keepPreviousData: params?.keepPreviousData,
     revalidateOnFocus: false,
   });

2-2: Prefer the stable mutate reference over wrapping with useCallback

mutate from SWR is already stable; you can avoid an extra closure and remove an unused React import.

-import { useCallback, useMemo } from 'react';
+import { useMemo } from 'react';
-  const revalidate = useCallback(() => swr.mutate(), [swr.mutate]);
+  const { mutate: revalidate } = swr;

Also applies to: 64-64


66-69: Comment typo and minor cleanup

Fix spelling and spacing.

-  // `swr.mutate` does not dedupe, N parallel calles will fire N revalidation requests.
-  //  To avoid this, we use `useThrottledEvent` to dedupe the revalidation requests.
+  // `swr.mutate` does not dedupe; N parallel calls will fire N revalidation requests.
+  // To avoid this, we use `useThrottledEvent` to dedupe the revalidation requests.

35-83: Add an explicit return type for the public hook

Per repo guidelines, public APIs should declare explicit return types. Define and export a UseSubscriptionResult type (using your canonical Subscription type) and annotate useSubscription.

If you want, I can draft the exact type using your @clerk/types Subscription shape and the SWR wrapper’s Mutate type.

📜 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 73fe6ff and f174b51.

📒 Files selected for processing (9)
  • packages/clerk-js/src/core/clerk.ts (1 hunks)
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts (2 hunks)
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts (1 hunks)
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx (2 hunks)
  • packages/react/src/isomorphicClerk.ts (1 hunks)
  • packages/shared/src/clerkEventBus.ts (1 hunks)
  • packages/shared/src/react/hooks/useSubscription.tsx (4 hunks)
  • packages/shared/src/react/hooks/useThrottledEvent.tsx (1 hunks)
  • packages/types/src/clerk.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/clerkEventBus.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/clerk.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.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/shared/src/clerkEventBus.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/clerk.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/clerkEventBus.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/clerk.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/clerkEventBus.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/clerk.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.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/shared/src/clerkEventBus.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/clerk.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.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/shared/src/clerkEventBus.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/CommerceSubscription.ts
  • packages/types/src/clerk.ts
  • packages/clerk-js/src/core/resources/CommerceCheckout.ts
  • packages/clerk-js/src/ui/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.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/contexts/components/Plans.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/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.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/contexts/components/Plans.tsx
  • packages/shared/src/react/hooks/useThrottledEvent.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
🧬 Code graph analysis (4)
packages/clerk-js/src/core/resources/CommerceCheckout.ts (1)
packages/types/src/commerce.ts (1)
  • ConfirmCheckoutParams (1184-1210)
packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)
packages/shared/src/react/hooks/useSubscription.tsx (1)
  • useSubscription (35-83)
packages/shared/src/react/hooks/useThrottledEvent.tsx (1)
packages/types/src/clerk.ts (1)
  • ClerkEventPayload (150-153)
packages/shared/src/react/hooks/useSubscription.tsx (3)
packages/types/src/clerk.ts (1)
  • ClerkEventPayload (150-153)
packages/react/src/isomorphicClerk.ts (2)
  • user (689-695)
  • organization (697-703)
packages/shared/src/react/hooks/useThrottledEvent.tsx (1)
  • useThrottledEvent (63-115)
⏰ 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). (7)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: triage
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (6)
packages/shared/src/clerkEventBus.ts (1)

7-8: LGTM: event key added and typed correctly

The new ResourceAction key aligns with ClerkEventPayload and preserves type safety.

packages/clerk-js/src/ui/contexts/components/Plans.tsx (1)

118-118: Verified: useSubscription listens to both checkout.confirm and subscriptionItem.cancel via useThrottledEvent.

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

88-89: Emit-on-success looks good.

Event is only emitted after a successful confirm, which avoids false-positive revalidations. No changes needed.


56-56: Public API: confirm changed to async Update its JSDoc to return Promise<this>, and audit all downstream call sites and documentation to ensure callers now await or handle the returned promise.

packages/shared/src/react/hooks/useSubscription.tsx (2)

1-2: Type-only imports look correct

Using import type { ... } and narrowing React imports is good.


26-26: Event triggers are correctly scoped

The event list matches the declared union in types and keeps the hook focused on pertinent mutations.

Comment on lines +44 to 54
const key = useMemo(
() =>
user?.id
? {
type: 'commerce-subscription',
userId: user.id,
args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
}
: null,
[user?.id, organization?.id, params?.for],
);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Don’t fetch before org context is ready (prevents wrong-target queries)

When params?.for === 'organization' but organization?.id is not yet available, the hook still returns a non-null SWR key and calls getSubscription({ orgId: undefined }). Gate the key until organization.id exists to avoid misrouted or failing requests.

Apply:

-  const key = useMemo(
-    () =>
-      user?.id
-        ? {
-            type: 'commerce-subscription',
-            userId: user.id,
-            args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
-          }
-        : null,
-    [user?.id, organization?.id, params?.for],
-  );
+  const key = useMemo(() => {
+    if (!user?.id) return null;
+    const isOrg = params?.for === 'organization';
+    if (isOrg && !organization?.id) return null;
+    return {
+      type: 'commerce-subscription' as const,
+      userId: user.id,
+      args: isOrg ? { orgId: organization!.id } : {},
+    };
+  }, [user?.id, organization?.id, params?.for]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const key = useMemo(
() =>
user?.id
? {
type: 'commerce-subscription',
userId: user.id,
args: { orgId: params?.for === 'organization' ? organization?.id : undefined },
}
: null,
[user?.id, organization?.id, params?.for],
);
const key = useMemo(() => {
if (!user?.id) return null;
const isOrg = params?.for === 'organization';
if (isOrg && !organization?.id) return null;
return {
type: 'commerce-subscription' as const,
userId: user.id,
args: isOrg ? { orgId: organization.id } : {},
};
}, [user?.id, organization?.id, params?.for]);
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useSubscription.tsx around lines 44 to 54,
the SWR key is created even when params?.for === 'organization' but
organization?.id is not yet available, which causes getSubscription to be called
with orgId: undefined; change the useMemo so it returns null when the user is
missing or when params?.for === 'organization' and organization?.id is
falsy—i.e., gate the key on organization?.id existence—so SWR won't fetch until
the org context is ready; ensure the dependency array still includes user?.id,
organization?.id, and params?.for.

Comment on lines +56 to +57
const serializedKey = useMemo(() => JSON.stringify(key), [key]);

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 “null” uniqueKey leak into event registry

JSON.stringify(null) is the string "null", which is truthy. This registers a shared listener for all not-ready hooks, wasting work and risking cross-instance coupling. Return undefined when the key is null so useThrottledEvent skips registration.

-  const serializedKey = useMemo(() => JSON.stringify(key), [key]);
+  const serializedKey = useMemo(() => (key ? JSON.stringify(key) : undefined), [key]);
🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/useSubscription.tsx around lines 56 to 57,
JSON.stringify(key) currently turns a null key into the string "null" which
causes a shared listener to be registered; change the memo so that when key is
null or undefined it returns undefined (not the string "null") and otherwise
returns the JSON string—this ensures useThrottledEvent will skip registration
for not-ready hooks.

@panteliselef panteliselef self-assigned this Sep 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant