Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Dec 14, 2025

Description

Removes SWR based fetching in favor of RQ.

Fixes: USER-4034

Related bug fixes: #7544

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

  • Refactor

    • Consolidated data fetching onto React Query, replacing legacy SWR compatibility layers with unified implementations.
  • Chores

    • Removed SWR-based runtime switch, promoted React Query core to runtime, and simplified build/test/type tooling.
    • Slightly increased bundle size threshold for a UI entry.
  • Tests

    • Simplified tests by removing environment branching and standardizing expectations across runs.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Dec 14, 2025

🦋 Changeset detected

Latest commit: 6b2cae1

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

This PR includes changesets to release 19 packages
Name Type
@clerk/shared Major
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/clerk-js Patch
@clerk/expo-passkeys Patch
@clerk/expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/localizations Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/react Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/ui 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 Dec 14, 2025

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

Project Deployment Review Updated (UTC)
clerk-js-sandbox Ready Ready Preview, Comment Jan 7, 2026 10:55pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 14, 2025

📝 Walkthrough

Walkthrough

This PR removes SWR variants and the environment-driven switchover, consolidating React Query implementations as the single data-fetching layer. It promotes @tanstack/query-core to a runtime dependency, deletes virtual-data-hooks type declarations and HookAliasPlugin logic, removes SWR re-exports and all *.swr.* modules, replaces virtual re-exports with in-file React Query hook implementations, and updates configs, tests, and providers to drop the global CLERK_USE_RQ flag and related SWR plumbing.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(shared): Remove SWR' clearly and concisely summarizes the primary change of this PR, which is the removal of SWR-based implementations in favor of React Query.
Linked Issues check ✅ Passed All coding requirements from USER-4034 are met: SWR files deleted, RQ files renamed, clerk-swr removed, plugins removed, SWR removed from package.json, and @tanstack/query-core promoted to dependencies.
Out of Scope Changes check ✅ Passed All changes in the PR are directly related to the objective of removing SWR and consolidating around React Query; no unrelated modifications detected.
Docstring Coverage ✅ Passed Docstring coverage is 90.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


📜 Recent review details

Configuration used: Repository YAML (base), Organization UI (inherited)

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 1a351ae and 6b2cae1.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (6)
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/contexts.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/ui/package.json
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
💤 Files with no reviewable changes (1)
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
🧰 Additional context used
📓 Path-based instructions (15)
**/*.{js,jsx,ts,tsx}

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

All code must pass ESLint checks with the project's configuration

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/package.json
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.{ts,tsx,js,jsx}

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

Follow established naming conventions (PascalCase for components, camelCase for variables)

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.tsx

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

**/*.tsx: Use error boundaries in React components
Minimize re-renders in React components

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

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.{md,tsx}

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

Update documentation for API changes

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components (e.g., 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
Separate UI components from business logic components
Use useState for simple state management in React components
Use useReducer for complex state logic in React components
Implement proper state initialization in React components
Use proper state updates with callbacks in React components
Implement proper state cleanup in React components
Use Context API for theme/authentication state management
Implement proper state persistence in React applications
Use React.memo for expensive components
Implement proper useCallback for handlers in React components
Use proper useMemo for expensive computations in React components
Implement proper virtualization for lists in React components
Use proper code splitting with React.lazy in React applications
Implement proper cleanup in useEffect hooks
Use proper refs for DOM access in React components
Implement proper event listener cleanup in React components
Use proper abort controllers for fetch in React components
Implement proper subscription cleanup in React components
Use proper HTML elements for semantic HTML in React components
Implement proper ARIA attributes for accessibility in React components
Use proper heading hierarchy in React components
Implement proper form labels in React components
Use proper button types in React components
Implement proper focus management for keyboard navigation in React components
Use proper keyboard shortcuts in React components
Implement proper tab order in React components
Use proper ...

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.{ts,tsx}

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

**/*.{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
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
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 in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/package.json
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

**/*: Only comment on issues that would block merging, ignore minor or stylistic concerns.
Restrict feedback to errors, security risks, or functionality-breaking problems.
Do not post comments on code style, formatting, or non-critical improvements.
Keep reviews short: flag only issues that make the PR unsafe to merge.
Group similar issues into a single comment instead of posting multiple notes.
Skip repetition: if a pattern repeats, mention it once at a summary level only.
Do not add general suggestions, focus strictly on merge-blocking concerns.
If there are no critical problems, respond with minimal approval (e.g., 'Looks good'). Do not add additional review.
Avoid line-by-line commentary unless it highlights a critical bug or security hole.
Highlight only issues that could cause runtime errors, data loss, or severe maintainability issues.
Ignore minor optimization opportunities, focus solely on correctness and safety.
Provide a top-level summary of critical blockers rather than detailed per-line notes.
Comment only when the issue must be resolved before merge, otherwise remain silent.
When in doubt, err on the side of fewer comments, brevity and blocking issues only.
Avoid posting any refactoring issues.

Files:

  • packages/shared/src/react/contexts.tsx
  • packages/clerk-js/src/test/create-fixtures.tsx
  • packages/shared/src/react/hooks/__tests__/wrapper.tsx
  • packages/ui/package.json
  • packages/ui/src/contexts/CoreClerkContextWrapper.tsx
packages/*/package.json

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

packages/*/package.json: Packages should export TypeScript types alongside runtime code
Follow semantic versioning for all packages

All packages must be published under @clerk namespace

packages/*/package.json: Framework packages should depend on @clerk/clerk-js for core functionality
@clerk/shared should be a common dependency for most packages in the monorepo

Files:

  • packages/ui/package.json
**/package.json

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

Use pnpm as the package manager for this monorepo

Files:

  • packages/ui/package.json
🧬 Code graph analysis (2)
packages/shared/src/react/contexts.tsx (1)
packages/shared/src/react/index.ts (1)
  • OrganizationProvider (9-9)
packages/clerk-js/src/test/create-fixtures.tsx (2)
packages/ui/src/contexts/CoreClerkContextWrapper.tsx (1)
  • CoreClerkContextWrapper (21-67)
packages/clerk-js/src/test/core-fixtures.ts (1)
  • clerkMock (249-256)
⏰ 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). (25)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/ui/src/contexts/CoreClerkContextWrapper.tsx (1)

14-17: No action needed. All callers of CoreClerkContextWrapper have been properly updated following the removal of the swrConfig prop. Both production usage (packages/ui/src/lazyModules/providers.tsx) and test usage (packages/clerk-js/src/test/create-fixtures.tsx) correctly pass only the clerk prop. The breaking change is complete and safe to merge.

packages/shared/src/react/contexts.tsx (1)

71-81: Breaking change properly implemented across all callers.

All usages of OrganizationProvider have been updated to match the new signature following the removal of the swrConfig prop. Verified across packages/react, packages/ui, and test files with no remaining references to swrConfig.


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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 14, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@7455

@clerk/upgrade

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

@clerk/vue

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

commit: 6b2cae1

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

🧹 Nitpick comments (14)
packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx (1)

508-538: LGTM! Consider simplifying the test name.

The expectation of at least 2 fetcher calls correctly reflects React Query's behavior where revalidating the paginated query also invalidates the infinite query variant sharing the same cache key base.

Since SWR has been completely removed, consider simplifying the test name by removing the now-redundant phrase "only for React Query":

-  it('revalidate propagates to infinite counterpart only for React Query', async () => {
+  it('revalidate propagates to infinite counterpart', async () => {
packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx (3)

64-64: Update test name to reflect SWR removal.

The test name mentions "only when using React Query" but since SWR has been completely removed in this PR, React Query is now always used. The conditional phrasing is misleading.

Consider updating the test name:

-  it('cascades revalidation for related queries only when using React Query', async () => {
+  it('cascades revalidation for related queries', async () => {

122-123: Remove redundant assertion.

Line 122 checks for ≥ 1 call, but line 123 immediately checks for ≥ 2 calls. The first assertion is redundant since ≥ 2 already implies ≥ 1.

Apply this diff:

-    await waitFor(() => expect(getAllSpy.mock.calls.length).toBeGreaterThanOrEqual(1));
     await waitFor(() => expect(getAllSpy.mock.calls.length).toBeGreaterThanOrEqual(2));

153-154: Remove redundant assertion.

Same issue as lines 122-123: line 153 checks for ≥ 1 call, but line 154 immediately checks for ≥ 2 calls. The first assertion is redundant.

Apply this diff:

-    await waitFor(() => expect(getAllSpy.mock.calls.length).toBeGreaterThanOrEqual(1));
     await waitFor(() => expect(getAllSpy.mock.calls.length).toBeGreaterThanOrEqual(2));
packages/shared/src/react/hooks/usePlanDetailsQuery.tsx (1)

8-11: Enhance JSDoc for better maintainability.

While this is an internal API, adding @param, @returns, and a brief description would help maintainers understand the hook's purpose and usage, especially given the migration from SWR to React Query.

Consider applying this enhancement:

 /**
  * @internal
+ * Internal hook to fetch plan details using React Query.
+ * @param params - Configuration for the plan details query
+ * @param params.planId - The ID of the plan to fetch
+ * @param params.initialPlan - Initial plan data to use before fetching
+ * @param params.keepPreviousData - Whether to keep previous data during refetches (default: true)
+ * @returns Plan details query result with data, error, loading and fetching states
  */
 export function __internal_usePlanDetailsQuery(params: UsePlanDetailsQueryParams = {}): PlanDetailsQueryResult {
packages/shared/src/react/hooks/useStatementQuery.tsx (1)

1-26: LGTM! Clean setup with minor optimization opportunity.

The imports, parameter handling, and context setup are well-structured. Type-only imports follow best practices for tree-shaking.

Optional refinement: Line 28 passes the entire params object to useBillingHookEnabled, which only expects { for?, enabled?, authenticated? }. While TypeScript's structural typing allows this, you could destructure only the needed fields for clarity:

-const billingEnabled = useBillingHookEnabled(params);
+const billingEnabled = useBillingHookEnabled({ for: forType, enabled: params.enabled });
packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts (4)

91-93: Stale comment references SWR.

The comment "wait until SWR mock finishes fetching" is outdated since SWR has been removed. Consider updating it to reflect the React Query implementation.

-    // wait until SWR mock finishes fetching
+    // wait until data finishes fetching
     await waitFor(() => expect(result.current.isLoading).toBe(false));

206-211: Stale comment references SWR.

Similar to the earlier comment, this reference to "SWR may refetch" should be updated since the implementation is now React Query-based.

-    // SWR may refetch the first page after size change; ensure both pages 1 and 2 were requested
+    // React Query may refetch the first page after size change; ensure both pages 1 and 2 were requested
     expect(fetcher.mock.calls.length).toBeGreaterThanOrEqual(2);

241-246: Stale comment references SWR mock.

This comment references "our SWR mock" which is no longer accurate.

-    // our SWR mock sets loading=false if key is null and not calling fetcher
+    // loading is false when disabled and fetcher is not called
     expect(fetcher).toHaveBeenCalledTimes(0);

677-680: Stale comment references SWR.

This comment mentions "SWR refetches all pages in infinite mode" but should reference React Query.

-    // Verify both pages were revalidated (SWR refetches all pages in infinite mode)
+    // Verify both pages were revalidated (React Query refetches all pages in infinite mode)
     const revalidatedPages = revalidateCalls.map(c => c.page);
packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx (1)

32-43: Harden sign-out detection + queryKey shape assumptions.
isSignedOut: user === null won’t trigger cleanup if the context ever yields undefined, and queryKey[3].args will throw if the key shape changes.

-  useClearQueriesOnSignOut({
-    isSignedOut: user === null, // works with the transitive state
+  useClearQueriesOnSignOut({
+    isSignedOut: user == null, // null or undefined
     authenticated,
     stableKeys: stableKey,
   });

   const query = useClerkQuery({
     queryKey,
     queryFn: ({ queryKey }) => {
-      const args = queryKey[3].args;
+      const args = (queryKey as typeof queryKey)[3]?.args;
       return clerk.billing.getPaymentAttempt(args);
     },
packages/shared/src/react/hooks/usePagesOrInfinite.tsx (1)

58-73: Avoid return undefined as any in queryFn (make the invariant explicit).
If fetcher is unexpectedly missing, you’ll silently cache undefined instead of surfacing a real misuse.

     queryFn: ({ queryKey }) => {
       const { args } = queryKey[3];

       if (!fetcher) {
-        return undefined as any;
+        throw new Error('usePagesOrInfinite: `fetcher` is required when queries are enabled.');
       }

       return fetcher(args);
     },

Also applies to: 90-96

packages/shared/src/react/billing/useStripeClerkLibs.tsx (1)

19-37: Consider exposing error state or adding error handling.

The hook returns null both when billing is disabled and when the query fails. Consumers cannot distinguish between "not yet loaded" and "failed to load" states.

If error handling is intentionally omitted for simplicity, this is acceptable for an internal hook. Otherwise, consider returning query.error or a loading state for better observability.

-export type UseStripeClerkLibsResult = StripeClerkLibs | null;
+export type UseStripeClerkLibsResult = {
+  data: StripeClerkLibs | null;
+  isLoading: boolean;
+  error: Error | null;
+};
packages/shared/src/react/billing/useInitializePaymentMethod.tsx (1)

54-73: Consider handling errors from initializePaymentMethod.

The callback propagates any thrown errors to callers, which is acceptable. However, if the API call fails, the query cache won't be updated, and consumers might see stale data. Consider whether failed attempts should invalidate the cache or if error state should be tracked.

If error handling is desired:

  const initializePaymentMethod = useCallback(async () => {
    if (!resource) {
      return undefined;
    }

-   const result = await resource.initializePaymentMethod({
-     gateway: 'stripe',
-   });
+   try {
+     const result = await resource.initializePaymentMethod({
+       gateway: 'stripe',
+     });
 
-   queryClient.setQueryData(queryKey, result);
+     queryClient.setQueryData(queryKey, result);
 
-   return result;
+     return result;
+   } catch (error) {
+     queryClient.invalidateQueries({ queryKey });
+     throw error;
+   }
  }, [queryClient, queryKey, resource]);
📜 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 395a4ca and 6ee75be.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (45)
  • .changeset/remove-swr-switches.md (1 hunks)
  • packages/shared/global.d.ts (0 hunks)
  • packages/shared/package.json (1 hunks)
  • packages/shared/src/react/billing/useInitializePaymentMethod.rq.tsx (0 hunks)
  • packages/shared/src/react/billing/useInitializePaymentMethod.swr.tsx (0 hunks)
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx (1 hunks)
  • packages/shared/src/react/billing/useStripeClerkLibs.rq.tsx (0 hunks)
  • packages/shared/src/react/billing/useStripeClerkLibs.swr.tsx (0 hunks)
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx (1 hunks)
  • packages/shared/src/react/billing/useStripeLoader.rq.tsx (0 hunks)
  • packages/shared/src/react/billing/useStripeLoader.swr.tsx (0 hunks)
  • packages/shared/src/react/billing/useStripeLoader.tsx (1 hunks)
  • packages/shared/src/react/clerk-swr.ts (0 hunks)
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx (2 hunks)
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx (3 hunks)
  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts (1 hunks)
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx (1 hunks)
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx (3 hunks)
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx (1 hunks)
  • packages/shared/src/react/hooks/index.ts (1 hunks)
  • packages/shared/src/react/hooks/useAPIKeys.swr.tsx (0 hunks)
  • packages/shared/src/react/hooks/useAPIKeys.ts (0 hunks)
  • packages/shared/src/react/hooks/usePagesOrInfinite.rq.tsx (0 hunks)
  • packages/shared/src/react/hooks/usePagesOrInfinite.swr.tsx (0 hunks)
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.rq.tsx (0 hunks)
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.swr.tsx (0 hunks)
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx (1 hunks)
  • packages/shared/src/react/hooks/usePlanDetailsQuery.rq.tsx (0 hunks)
  • packages/shared/src/react/hooks/usePlanDetailsQuery.swr.tsx (0 hunks)
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx (1 hunks)
  • packages/shared/src/react/hooks/useStatementQuery.rq.tsx (0 hunks)
  • packages/shared/src/react/hooks/useStatementQuery.swr.tsx (0 hunks)
  • packages/shared/src/react/hooks/useStatementQuery.tsx (1 hunks)
  • packages/shared/src/react/hooks/useSubscription.rq.tsx (0 hunks)
  • packages/shared/src/react/hooks/useSubscription.swr.tsx (0 hunks)
  • packages/shared/src/react/hooks/useSubscription.tsx (1 hunks)
  • packages/shared/src/react/providers/SWRConfigCompat.rq.tsx (0 hunks)
  • packages/shared/src/react/providers/SWRConfigCompat.swr.tsx (0 hunks)
  • packages/shared/src/react/providers/SWRConfigCompat.tsx (1 hunks)
  • packages/shared/src/types/virtual-data-hooks.d.ts (0 hunks)
  • packages/shared/tsconfig.json (1 hunks)
  • packages/shared/tsdown.config.mts (0 hunks)
  • packages/shared/vitest.config.mts (0 hunks)
  • packages/shared/vitest.setup.mts (0 hunks)
💤 Files with no reviewable changes (26)
  • packages/shared/global.d.ts
  • packages/shared/src/react/hooks/useAPIKeys.ts
  • packages/shared/src/react/providers/SWRConfigCompat.swr.tsx
  • packages/shared/vitest.setup.mts
  • packages/shared/src/react/hooks/useStatementQuery.rq.tsx
  • packages/shared/src/react/clerk-swr.ts
  • packages/shared/src/react/hooks/useSubscription.rq.tsx
  • packages/shared/src/react/hooks/useSubscription.swr.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.rq.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.rq.tsx
  • packages/shared/vitest.config.mts
  • packages/shared/tsdown.config.mts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.swr.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.swr.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.swr.tsx
  • packages/shared/src/react/hooks/useAPIKeys.swr.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.rq.tsx
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.rq.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.rq.tsx
  • packages/shared/src/react/billing/useStripeLoader.rq.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.swr.tsx
  • packages/shared/src/react/hooks/useStatementQuery.swr.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.swr.tsx
  • packages/shared/src/react/billing/useStripeLoader.swr.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.rq.tsx
  • packages/shared/src/types/virtual-data-hooks.d.ts
🧰 Additional context used
📓 Path-based instructions (18)
**/*.{js,jsx,ts,tsx}

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

All code must pass ESLint checks with the project's configuration

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/tsconfig.json
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/package.json
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{ts,tsx,js,jsx}

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

Follow established naming conventions (PascalCase for components, camelCase for variables)

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{test,spec}.{ts,tsx,js,jsx}

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

**/*.{test,spec}.{ts,tsx,js,jsx}: Unit tests are required for all new functionality
Verify proper error handling and edge cases
Include tests for all new features

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}

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

Use real Clerk instances for integration tests

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{ts,tsx}

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

**/*.{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
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
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 in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts
  • packages/shared/src/react/hooks/index.ts
  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/tsconfig.json
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/package.json
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/index.ts

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

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

Files:

  • packages/shared/src/react/hooks/index.ts
**/*.tsx

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

**/*.tsx: Use error boundaries in React components
Minimize re-renders in React components

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

Files:

  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{md,tsx}

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

Update documentation for API changes

Files:

  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{jsx,tsx}

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

**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components (e.g., 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
Separate UI components from business logic components
Use useState for simple state management in React components
Use useReducer for complex state logic in React components
Implement proper state initialization in React components
Use proper state updates with callbacks in React components
Implement proper state cleanup in React components
Use Context API for theme/authentication state management
Implement proper state persistence in React applications
Use React.memo for expensive components
Implement proper useCallback for handlers in React components
Use proper useMemo for expensive computations in React components
Implement proper virtualization for lists in React components
Use proper code splitting with React.lazy in React applications
Implement proper cleanup in useEffect hooks
Use proper refs for DOM access in React components
Implement proper event listener cleanup in React components
Use proper abort controllers for fetch in React components
Implement proper subscription cleanup in React components
Use proper HTML elements for semantic HTML in React components
Implement proper ARIA attributes for accessibility in React components
Use proper heading hierarchy in React components
Implement proper form labels in React components
Use proper button types in React components
Implement proper focus management for keyboard navigation in React components
Use proper keyboard shortcuts in React components
Implement proper tab order in React components
Use proper ...

Files:

  • packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/providers/SWRConfigCompat.tsx
  • packages/shared/src/react/billing/useStripeClerkLibs.tsx
  • packages/shared/src/react/hooks/usePlanDetailsQuery.tsx
  • packages/shared/src/react/hooks/useStatementQuery.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/useSubscription.tsx
  • packages/shared/src/react/hooks/usePagesOrInfinite.tsx
  • packages/shared/src/react/billing/useInitializePaymentMethod.tsx
  • packages/shared/src/react/billing/useStripeLoader.tsx
  • packages/shared/src/react/hooks/createBillingPaginatedHook.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
**/*.{test,spec}.{jsx,tsx}

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

**/*.{test,spec}.{jsx,tsx}: Use React Testing Library for unit testing React components
Test component behavior, not implementation details
Use proper test queries in React Testing Library tests
Implement proper test isolation in React component tests
Use proper test coverage in React component tests
Test component interactions in integration tests
Use proper test data in React component tests
Implement proper test setup in React component tests
Use proper test cleanup in React component tests
Implement proper test assertions in React component tests
Use proper test structure for React component tests

Files:

  • packages/shared/src/react/hooks/__tests__/useAPIKeys.spec.tsx
  • packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx
  • packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx
  • packages/shared/src/react/hooks/__tests__/usePlans.spec.tsx
packages/*/package.json

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

packages/*/package.json: Packages should export TypeScript types alongside runtime code
Follow semantic versioning for all packages

All packages must be published under @clerk namespace

packages/*/package.json: Framework packages should depend on @clerk/clerk-js for core functionality
@clerk/shared should be a common dependency for most packages in the monorepo

Files:

  • packages/shared/package.json
**/package.json

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

Use pnpm as the package manager for this monorepo

Files:

  • packages/shared/package.json
🧬 Code graph analysis (5)
packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx (7)
packages/shared/src/react/hooks/usePaymentAttemptQuery.types.ts (2)
  • UsePaymentAttemptQueryParams (7-30)
  • PaymentAttemptQueryResult (35-52)
packages/shared/src/react/index.ts (3)
  • useClerkInstanceContext (12-12)
  • useUserContext (18-18)
  • useOrganizationContext (15-15)
packages/shared/src/react/hooks/usePaymentAttemptQuery.shared.ts (1)
  • usePaymentAttemptQueryCacheKeys (7-32)
packages/shared/src/react/hooks/useBillingHookEnabled.ts (1)
  • useBillingHookEnabled (7-27)
packages/shared/src/react/hooks/useClearQueriesOnSignOut.ts (1)
  • useClearQueriesOnSignOut (28-64)
packages/shared/src/react/clerk-rq/useQuery.ts (1)
  • useClerkQuery (39-41)
packages/shared/src/react/clerk-rq/keep-previous-data.ts (1)
  • defineKeepPreviousDataFn (4-11)
packages/shared/src/react/billing/useStripeClerkLibs.tsx (4)
packages/shared/src/react/hooks/index.ts (1)
  • useClerk (10-10)
packages/shared/src/react/hooks/useBillingHookEnabled.ts (1)
  • useBillingHookEnabled (7-27)
packages/shared/src/react/clerk-rq/useQuery.ts (1)
  • useClerkQuery (39-41)
packages/shared/src/react/clerk-rq/keep-previous-data.ts (1)
  • defineKeepPreviousDataFn (4-11)
packages/shared/src/react/hooks/useStatementQuery.tsx (6)
packages/shared/src/react/hooks/useStatementQuery.types.ts (2)
  • UseStatementQueryParams (6-29)
  • StatementQueryResult (34-51)
packages/shared/src/react/hooks/useStatementQuery.shared.ts (1)
  • useStatementQueryCacheKeys (7-32)
packages/shared/src/react/hooks/useBillingHookEnabled.ts (1)
  • useBillingHookEnabled (7-27)
packages/shared/src/react/hooks/useClearQueriesOnSignOut.ts (1)
  • useClearQueriesOnSignOut (28-64)
packages/shared/src/react/clerk-rq/useQuery.ts (1)
  • useClerkQuery (39-41)
packages/shared/src/react/clerk-rq/keep-previous-data.ts (1)
  • defineKeepPreviousDataFn (4-11)
packages/shared/src/react/billing/useStripeLoader.tsx (5)
packages/shared/src/react/billing/useStripeClerkLibs.tsx (1)
  • UseStripeClerkLibsResult (14-14)
packages/clerk-js/src/core/resources/BillingCheckout.ts (1)
  • externalGatewayId (142-144)
packages/shared/src/react/hooks/useBillingHookEnabled.ts (1)
  • useBillingHookEnabled (7-27)
packages/shared/src/react/clerk-rq/useQuery.ts (1)
  • useClerkQuery (39-41)
packages/shared/src/react/clerk-rq/keep-previous-data.ts (1)
  • defineKeepPreviousDataFn (4-11)
packages/shared/src/react/hooks/createBillingPaginatedHook.tsx (1)
packages/react/src/isomorphicClerk.ts (1)
  • organization (737-743)
⏰ 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: Unit Tests (shared, clerk-js, RQ)
  • GitHub Check: Unit Tests (**)
  • GitHub Check: Static analysis
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (22)
packages/shared/src/react/hooks/index.ts (1)

24-24: LGTM! Comment accurately reflects the SWR removal.

The updated comment correctly documents that only React Query implementations are now centralized here, aligning with the PR's goal to completely remove SWR.

packages/shared/src/react/hooks/__tests__/createBillingPaginatedHook.spec.tsx (1)

311-311: LGTM! Correct expectation after sign-out.

The unconditional expectation that isLoading is false after sign-out is correct for React Query behavior. When the user becomes null, the authenticated hook correctly transitions to a non-loading state.

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

12-15: LGTM! Clean parameter handling and ID resolution.

The use of nullish coalescing and optional chaining follows TypeScript best practices, and the fallback logic correctly prioritizes explicit planId over initialPlan.id.


17-37: Well-structured React Query configuration.

The query setup is correct:

  • Conditional execution via enabled properly gates the query
  • The defensive throw in queryFn provides type narrowing and safeguards against future logic changes
  • initialDataUpdatedAt: 0 appropriately marks initial data as stale for refetching
  • placeholderData with defineKeepPreviousDataFn handles the keepPreviousData behavior correctly
packages/shared/src/react/hooks/useStatementQuery.tsx (2)

28-36: LGTM! Proper enable gating and cleanup.

The query enable logic correctly combines statementId presence with billing enablement. The sign-out cleanup properly removes cached queries using matching stable keys and authenticated flags.


38-49: LGTM! Solid React Query implementation.

The query implementation is well-structured with appropriate caching strategy (1-minute stale time) and optional placeholder data for smooth UX during refetches.

The defensive statementId check on line 41 is necessary for TypeScript type narrowing, even though the enabled flag prevents the queryFn from executing when statementId is falsy. Without this check, TypeScript would not narrow statementId from string | null to string for the API call on line 44.

packages/shared/src/react/hooks/createBillingPaginatedHook.tsx (1)

140-149: LGTM! Clean simplification of the cache key structure.

The removal of the environment-based key selection (_orgId vs orgId) in favor of a consistent orgId property aligns well with the PR's objective to eliminate __CLERK_USE_RQ__ branching.

packages/shared/tsconfig.json (1)

25-30: LGTM! Clean simplification of TypeScript configuration.

The consolidation from multiple granular virtual:data-hooks/* path mappings to a single @/* alias, along with removing virtual-data-hooks.d.ts from includes, correctly reflects the removal of the virtual module infrastructure.

.changeset/remove-swr-switches.md (1)

1-5: Appropriate major version bump for breaking changes.

The major designation is correct given that:

  1. SWR-based hooks are being removed (breaking for any consumers using them)
  2. @tanstack/query-core is promoted to a runtime dependency (new peer requirement)

The changeset description accurately summarizes the scope of changes.

packages/shared/src/react/hooks/__tests__/usePagesOrInfinite.spec.ts (1)

725-726: LGTM! Correct unconditional assertion after SWR removal.

The test now unconditionally expects the fetcher to be called at least twice during revalidation cascading, which is the expected React Query behavior. This aligns with the removal of environment-based branching.

packages/shared/src/react/hooks/__tests__/useSubscription.spec.tsx (3)

104-112: Good: sign-out now always clears data (no env-branching).
This matches the PR goal of removing SWR-driven divergent behavior.


125-133: Good: sign-out clears data even with keepPreviousData=true.
This is an important regression guard now that only React Query behavior remains.


150-164: Good: isLoading stays false during refetch when keepPreviousData=true.
This aligns with React Query’s typical “background refetch” semantics (isFetching true while isLoading false).

packages/shared/src/react/hooks/usePaymentAttemptQuery.tsx (1)

12-55: LGTM: consolidated RQ hook wiring + sign-out query cleanup is consistent with the new pattern.
Enablement (billingEnabled + id present), cache keys, and staleTime all look reasonable.

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

38-76: Good: query enablement + keepPreviousData + SWR-compatible error normalization.
The placeholderData: defineKeepPreviousDataFn(keepPreviousData && queriesEnabled) bit is especially clean.

packages/shared/src/react/billing/useStripeClerkLibs.tsx (3)

1-6: LGTM!

The imports are well-organized with type-only imports properly separated, and the dependencies align with the hook's requirements.


8-14: LGTM!

Type definitions are clean with proper use of typeof for deriving the function type and explicit export of the result type for consumers.


39-39: LGTM!

The internal alias export pattern aligns with the PR's migration approach and the @internal JSDoc annotation.

packages/shared/src/react/billing/useInitializePaymentMethod.tsx (4)

1-8: LGTM!

Imports are appropriate and well-organized, using type-only imports where applicable.


10-17: LGTM!

Type definitions are clear and properly exported for consumers. The result type correctly reflects both the cached data and the imperative trigger function.


22-52: LGTM!

The hook implementation is well-structured:

  • Proper resource selection based on for type
  • Memoized queryKey prevents unnecessary re-renders
  • Defensive null check in queryFn is good practice
  • Query options (staleTime, refetchOnWindowFocus, placeholderData) are appropriate for this use case

76-76: LGTM!

The internal alias export is consistent with the pattern used across the billing hooks in this PR.

Comment on lines +20 to +49
function useStripeLoader(options: StripeLoaderOptions): UseStripeLoaderResult {
const { stripeClerkLibs, externalGatewayId, stripePublishableKey } = options;

const queryKey = useMemo(() => {
return ['stripe-sdk', { externalGatewayId, stripePublishableKey }] as const;
}, [externalGatewayId, stripePublishableKey]);

const billingEnabled = useBillingHookEnabled({ authenticated: true });

const isEnabled = Boolean(stripeClerkLibs && externalGatewayId && stripePublishableKey) && billingEnabled;

const query = useClerkQuery({
queryKey,
queryFn: () => {
if (!stripeClerkLibs || !externalGatewayId || !stripePublishableKey) {
return null;
}

return stripeClerkLibs.loadStripe(stripePublishableKey, {
stripeAccount: externalGatewayId,
});
},
enabled: isEnabled,
staleTime: 1_000 * 60,
refetchOnWindowFocus: false,
placeholderData: defineKeepPreviousDataFn(true),
});

return query.data;
}
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 | 🟠 Major

Don’t always keep previous Stripe instance across key/account changes.
Unconditional keepPreviousData here can transiently return the wrong Stripe object when inputs change.

   const query = useClerkQuery({
     queryKey,
     queryFn: () => {
       if (!stripeClerkLibs || !externalGatewayId || !stripePublishableKey) {
         return null;
       }
       return stripeClerkLibs.loadStripe(stripePublishableKey, {
         stripeAccount: externalGatewayId,
       });
     },
     enabled: isEnabled,
     staleTime: 1_000 * 60,
     refetchOnWindowFocus: false,
-    placeholderData: defineKeepPreviousDataFn(true),
+    placeholderData: defineKeepPreviousDataFn(isEnabled),
   });
🤖 Prompt for AI Agents
In packages/shared/src/react/billing/useStripeLoader.tsx around lines 20 to 49,
the query unconditionally keeps the previous Stripe instance via
placeholderData: defineKeepPreviousDataFn(true) which can return the wrong
Stripe object when the key/account changes; change this so previous data is not
kept across key/account changes by disabling keep-previous behavior (remove the
placeholderData or set it to defineKeepPreviousDataFn(false) / set
keepPreviousData: false) so the query returns null or the new instance
immediately when inputs change.

Comment on lines +16 to +21
const [paginatedPage, setPaginatedPage] = useState(config.initialPage ?? 1);

// Cache initialPage and initialPageSize until unmount
const initialPageRef = useRef(config.initialPage ?? 1);
const pageSizeRef = useRef(config.pageSize ?? 10);

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 | 🟠 Major

Fix initialPage handling (page can become 0; infinite page and next/prev break when initialPage ≠ 1).
Current math will misreport page and can compute incorrect hasNextPage/hasPreviousPage for offset starts.

-  const [paginatedPage, setPaginatedPage] = useState(config.initialPage ?? 1);
+  const initialPage = Math.max(1, config.initialPage ?? 1);
+  const [paginatedPage, setPaginatedPage] = useState(initialPage);
 ...
-  const initialPageRef = useRef(config.initialPage ?? 1);
+  const initialPageRef = useRef(initialPage);
 ...
-        page: validPages.length > 0 ? validPages.length : initialPageRef.current,
+        page:
+          validPages.length > 0 ? initialPageRef.current + validPages.length - 1 : initialPageRef.current,
       };
     }
 ...
-  const fetchNext = useCallback(() => {
+  const fetchNext = useCallback(() => {
     if (triggerInfinite) {
       void infiniteQuery.fetchNextPage({ cancelRefetch: false });
       return;
     }
-    setPaginatedPage(n => Math.max(0, n + 1));
+    setPaginatedPage(n => Math.max(initialPageRef.current, n + 1));
   }, [infiniteQuery, triggerInfinite]);

   const fetchPrevious = useCallback(() => {
     if (triggerInfinite) {
       // not natively supported by forward-only pagination; noop
       return;
     }
-    setPaginatedPage(n => Math.max(0, n - 1));
+    setPaginatedPage(n => Math.max(initialPageRef.current, n - 1));
   }, [triggerInfinite]);

   const offsetCount = (initialPageRef.current - 1) * pageSizeRef.current;
-  const pageCount = Math.ceil((count - offsetCount) / pageSizeRef.current);
+  const pageCount = Math.ceil(Math.max(0, count - offsetCount) / pageSizeRef.current);
   const hasNextPage = triggerInfinite
     ? Boolean(infiniteQuery.hasNextPage)
-    : count - offsetCount * pageSizeRef.current > page * pageSizeRef.current;
+    : count > page * pageSizeRef.current;
   const hasPreviousPage = triggerInfinite
     ? Boolean(infiniteQuery.hasPreviousPage)
-    : (page - 1) * pageSizeRef.current > offsetCount * pageSizeRef.current;
+    : page > initialPageRef.current;

Also applies to: 114-133, 185-209

Comment on lines +82 to +83
const infiniteQuery = useClerkInfiniteQuery<ClerkPaginatedResponse<any>, any, any, typeof infiniteQueryKey, any>({
queryKey: infiniteQueryKey,
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 | 🟠 Major

Tighten exported typing (remove any casts on revalidate / setData, and reduce any generics).
Since usePagesOrInfinite is exported, the as any surface area will leak and defeat type-safety guarantees.

Also applies to: 232-255

🤖 Prompt for AI Agents
In packages/shared/src/react/hooks/usePagesOrInfinite.tsx around lines 82-83
(and similarly lines 232-255), the call to useClerkInfiniteQuery and the hook’s
exported API use broad any generics and cast revalidate/setData to any; tighten
the exported typing by introducing proper generic type parameters for the hook
(e.g., Item and Page/Response types that map to ClerkPaginatedResponse<Item>),
use those types as the generics for useClerkInfiniteQuery instead of any, and
remove the as any casts on revalidate and setData by giving them the correct
typed signatures (e.g., revalidate: () =>
Promise<void|ClerkPaginatedResponse<Item>> or the exact return type, and
setData: (updater: UpdaterFunction<Page[]|undefined>) => void) so the hook’s
return type is fully typed and no any leaks occur. Ensure to propagate these
types through all internal calls and the exported return type so the hook
remains type-safe for consumers.

Comment on lines +51 to +57
return {
data: query.data,
error: (query.error ?? null) as StatementQueryResult['error'],
isLoading: query.isLoading,
isFetching: query.isFetching,
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's read the useStatementQuery.tsx file to understand context
head -70 packages/shared/src/react/hooks/useStatementQuery.tsx | tail -30

Repository: clerk/javascript

Length of output: 878


🏁 Script executed:

# Find the useClerkQuery hook definition and its error type
rg -n "useClerkQuery" packages/shared/src/react -A 5 -B 2 | head -50

Repository: clerk/javascript

Length of output: 4435


🏁 Script executed:

# Find StatementQueryResult type definition
rg -n "StatementQueryResult" packages/shared/src/react -B 3 -A 5 | head -60

Repository: clerk/javascript

Length of output: 2965


🏁 Script executed:

# Search for ClerkAPIResponseError usage and definition
rg -n "ClerkAPIResponseError" packages/shared/src -B 2 -A 2 | head -50

Repository: clerk/javascript

Length of output: 3806


🏁 Script executed:

# Read the complete StatementQueryResult type definition
cat -n packages/shared/src/react/hooks/useStatementQuery.types.ts | sed -n '34,50p'

Repository: clerk/javascript

Length of output: 765


🏁 Script executed:

# Find the useClerkQuery definition and its return type
rg -n "function useClerkQuery|export.*useClerkQuery" packages/shared/src/react/clerk-rq -A 30 -B 2 | head -80

Repository: clerk/javascript

Length of output: 3129


🏁 Script executed:

# Check the types for useClerkQuery more specifically
rg -n "useClerkQuery" packages/shared/src/react/clerk-rq -l

Repository: clerk/javascript

Length of output: 218


🏁 Script executed:

# Find DefaultError definition from React Query
rg -n "DefaultError" packages/shared/src/react/clerk-rq -B 2 -A 2

Repository: clerk/javascript

Length of output: 12019


🏁 Script executed:

# Check CommonQueryResult type definition
rg -n "CommonQueryResult" packages/shared/src/react/clerk-rq -B 2 -A 5

Repository: clerk/javascript

Length of output: 4486


🏁 Script executed:

# Check useBaseQuery to understand error handling
rg -n "useBaseQuery" packages/shared/src/react/clerk-rq/useBaseQuery.ts -A 40 | head -60

Repository: clerk/javascript

Length of output: 2744


🏁 Script executed:

# Search for clerk.billing implementation
rg -n "billing\.getStatement" packages/shared/src -A 5 -B 2 | head -50

Repository: clerk/javascript

Length of output: 1402


🏁 Script executed:

# Check if there's error handling wrapper around Clerk API calls
rg -n "getStatement" packages/shared/src -B 3 -A 10 | head -80

Repository: clerk/javascript

Length of output: 4192


🏁 Script executed:

# Look for any error mappers or transformers in useClerkQuery or related files
rg -n "error.*transform|mapError|onError" packages/shared/src/react/clerk-rq -B 2 -A 3

Repository: clerk/javascript

Length of output: 42


Pass explicit error type to useClerkQuery or add type narrowing for the error.

The type assertion on line 53 assumes query.error is typed as ClerkAPIResponseError, but useClerkQuery is called without an explicit TError parameter, defaulting to React Query's DefaultError. This creates a type mismatch:

  • clerk.billing.getStatement() is expected to throw ClerkAPIResponseError (based on Clerk SDK patterns)
  • The manual error throw at line 42 is a plain Error, not ClerkAPIResponseError
  • The assertion hides this type safety issue

Either:

  1. Pass explicit type to useClerkQuery: useClerkQuery<BillingStatementResource, ClerkAPIResponseError>({ ... })
  2. Or add a type guard: error: isClerkAPIResponseError(query.error) ? query.error : null

Copy link
Contributor

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

Thank you ❣️

@Ephem
Copy link
Member

Ephem commented Dec 18, 2025

We've found a few last outstanding bugs in the RQ implementation so I think we should hold this until we've fixed those. I've pinged you elsewhere with details @jacekradko. 😄

jacekradko and others added 2 commits January 7, 2026 14:36
Prevent duplicate telemetry events by moving the clerk.telemetry.record
call out of the render path into a useEffect with a ref guard, ensuring
the event only fires once when clerk becomes available.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@jacekradko
Copy link
Member Author

!allow-major

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