Skip to content

fix(clerk-js, shared, nextjs): Improve typesafety of useCheckout #6473

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 5, 2025

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Aug 5, 2025

Description

Checklist

  • pnpm test runs as expected.
  • pnpm build runs as expected.
  • (If applicable) JSDoc comments have been added or updated for any package exports
  • (If applicable) Documentation has been updated

Type of change

  • 🐛 Bug fix
  • 🌟 New feature
  • 🔨 Breaking change
  • 📖 Refactoring / dependency upgrade / documentation
  • other:

Summary by CodeRabbit

  • New Features

    • Improved type safety and validation for the checkout experience in billing beta, ensuring more accurate state handling and error reporting.
  • Bug Fixes

    • Enhanced logic for displaying components based on checkout status, ensuring correct rendering behavior.
  • Tests

    • Added comprehensive tests to validate the new type rules and state correlations for the checkout process.
  • Chores

    • Updated package versions for several components to incorporate the latest changes.

@panteliselef panteliselef requested a review from a team August 5, 2025 11:14
@panteliselef panteliselef self-assigned this Aug 5, 2025
Copy link

vercel bot commented Aug 5, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 5, 2025 11:34am

Copy link

changeset-bot bot commented Aug 5, 2025

🦋 Changeset detected

Latest commit: 369f00c

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 Minor
@clerk/nextjs Minor
@clerk/clerk-react Minor
@clerk/clerk-js Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing 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

Copy link

pkg-pr-new bot commented Aug 5, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 369f00c

Copy link
Contributor

coderabbitai bot commented Aug 5, 2025

📝 Walkthrough

Walkthrough

This set of changes focuses on strengthening type safety and discriminated union typing for the useCheckout hook, primarily within the billing beta feature. The return type of useCheckout is made stricter, ensuring a closer correlation between the checkout status and the presence or absence of related properties. Type-level tests are added to validate these discriminated unions and property correlations. Some conditional rendering logic in UI components is updated to use the new status-based approach. Package versions for several Clerk-related packages are incremented, reflecting these updates.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~18 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6048ddf and 369f00c.

📒 Files selected for processing (1)
  • packages/shared/src/react/hooks/useCheckout.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/shared/src/react/hooks/useCheckout.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)

🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
  • 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 src/utils.ts and explain its main purpose.
    • @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 comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • 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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🔭 Outside diff range comments (1)
packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx (1)

64-78: Critical: Missing error in dependency array could cause stale error states.

While removing the optional chaining aligns with the discriminated union guarantees, removing error from the dependency array is problematic. If the error content changes while fetchStatus remains 'error', the memoized value won't update, potentially showing outdated error information.

   const internalFetchStatus = useMemo(() => {
     if (fetchStatus === 'error') {
       const errorCodes = error.errors.map(e => e.code);
 
       if (errorCodes.includes('missing_payer_email')) {
         return 'missing_payer_email';
       }
 
       if (errorCodes.includes('invalid_plan_change')) {
         return 'invalid_plan_change';
       }
     }
 
     return fetchStatus;
-  }, [fetchStatus]);
+  }, [fetchStatus, error]);
🧹 Nitpick comments (2)
packages/shared/src/react/hooks/useCheckout.ts (1)

134-136: Consider removing the type assertion for better type safety.

Type assertions bypass TypeScript's type checking. Since the checkout object is constructed to match the return type, TypeScript should be able to infer it correctly without the assertion.

   return {
     checkout,
-  } as __experimental_UseCheckoutReturn;
+  };

If the type assertion is necessary due to TypeScript inference limitations with the discriminated unions, consider adding a comment explaining why it's needed.

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

1-86: Consider adding runtime tests for the updated component behavior.

While type-level tests were added for the hook, consider adding runtime tests to verify that the FetchStatus component correctly handles the discriminated union states and that the memoization works as expected with different error scenarios.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3d073e and 6048ddf.

📒 Files selected for processing (5)
  • .changeset/brown-wings-shake.md (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx (2 hunks)
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts (2 hunks)
  • packages/shared/src/react/hooks/useCheckout.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
packages/clerk-js/src/ui/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/clerk-js-ui.mdc)

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

Files:

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

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

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

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx
**/*.{jsx,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

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

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

Files:

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

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

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

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx
**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/react.mdc)

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

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.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.

Files:

  • packages/clerk-js/src/ui/components/Checkout/CheckoutForm.tsx
  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
  • packages/shared/src/react/hooks/useCheckout.ts
  • packages/clerk-js/src/ui/components/Checkout/CheckoutPage.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Unit tests should use Jest or Vitest as the test runner.

Files:

  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
**/__tests__/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/typescript.mdc)

**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces

Files:

  • packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/brown-wings-shake.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
packages/shared/src/react/hooks/useCheckout.ts (3)

31-39: LGTM! Well-structured discriminated union for error states.

The FetchStatusAndError type correctly enforces that error is only present when fetchStatus is 'error', and null otherwise. This prevents accidental access to error properties in non-error states.


46-52: Consider using explicit type extension for clarity.

The discriminated union is well-designed. For better readability, consider explicitly extending the type instead of using the spread operator with the type alias.

 type CheckoutPropertiesPerStatus =
   | ({
       status: Extract<__experimental_CheckoutCacheState['status'], 'needs_initialization'>;
     } & ForceNull<CheckoutProperties>)
   | ({
       status: Extract<__experimental_CheckoutCacheState['status'], 'needs_confirmation' | 'completed'>;
-    } & CheckoutProperties);
+    } & CheckoutProperties);

Actually, the current implementation is fine. The spread operator with type alias is a common pattern in TypeScript.


96-118: Good use of explicit typing for discriminated union support.

The explicit type annotation on useMemo helps TypeScript understand the discriminated union pattern and ensures type safety when accessing properties based on the checkout state.

packages/shared/src/react/hooks/__tests__/useCheckout.type.spec.ts (2)

163-252: Excellent comprehensive type-level tests for discriminated unions!

The test suite thoroughly validates:

  • Correlation between fetchStatus and error presence
  • Property nullability based on status values
  • Preservation of method types across all states

This provides strong guarantees that the discriminated unions work as intended.


196-203: No action needed: paymentSource is correctly typed as null | undefined.

In the CommerceCheckoutResource definition, paymentSource is declared as optional (paymentSource?: …). As a result, its initialization state may legitimately be undefined in addition to null, whereas all other (required) properties are strictly null.

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

279-286: Good adaptation to the new discriminated union pattern.

The change from checking id to explicitly checking status === 'needs_initialization' is more semantically correct and aligns with the stricter typing of the useCheckout hook.

.changeset/brown-wings-shake.md (1)

1-8: LGTM! Appropriate version bumps for the type safety improvements.

The changeset correctly identifies this as a minor change for packages that export the hook and a patch for the consuming package. The description clearly communicates the improvement.

@panteliselef panteliselef merged commit 9368daf into main Aug 5, 2025
38 checks passed
@panteliselef panteliselef deleted the elef/strict-return-useCheckout branch August 5, 2025 18:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants