Skip to content

Conversation

panteliselef
Copy link
Member

@panteliselef panteliselef commented Sep 3, 2025

Description

Proper fix for #6688 as it propagate promise results to prepare calls for SignIn and SignUp to allow request cache to work properly.

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

  • Bug Fixes

    • Fixed an issue where prepare requests ran only once so users now reliably receive fresh OTPs for sign-in and sign-up.
  • Refactor

    • Centralized and improved error handling across email/phone/code verification flows for more consistent reporting and recovery.
  • Tests

    • Relaxed tests to accept the enhanced fetch options (including success/error handlers) for greater flexibility.

@panteliselef panteliselef self-assigned this Sep 3, 2025
Copy link

changeset-bot bot commented Sep 3, 2025

🦋 Changeset detected

Latest commit: 51340a1

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

This PR includes changesets to release 3 packages
Name Type
@clerk/clerk-js Patch
@clerk/chrome-extension Patch
@clerk/clerk-expo 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

vercel bot commented Sep 3, 2025

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

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

Copy link

pkg-pr-new bot commented Sep 3, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 51340a1

Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Walkthrough

Adds an optional onError callback to useFetch, updates SignIn and SignUp code-entry components to use useFetch onSuccess/onError callbacks (removing inline .catch handlers), adjusts tests to accept additional useFetch options, and adds a patch changeset documenting a prepare-once bug fix.

Changes

Cohort / File(s) Summary of Changes
Changeset
.changeset/crazy-days-tan.md
Adds a patch changeset entry documenting a bug fix where prepare API fired only once, preventing fresh OTP codes.
Hook: useFetch
packages/clerk-js/src/ui/hooks/useFetch.ts
Adds optional options.onError?: (error: Error) => void; invokes it after setting internal error state when fetch fails.
SignIn prepare
packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
Replaces inline then/catch in guarded fetch path with useFetch callbacks: onSuccess now calls props.onFactorPrepare(), onError forwards errors to handleError(...). Fetcher returns the prepare promise directly.
SignUp email/phone prepare
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx, packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx
Remove per-call .catch from prepare fetchers; add onError: err => handleError(err, [], card.setError) and rely on centralized onError or existing prepare helper catches. staleTime: 100 retained where present.
Tests
packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx
Relax assertions to expect onSuccess and onError functions in useFetch call options via expect.objectContaining, allowing extra keys in the third argument.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant UI as SignInFactorOneCodeForm
  participant Hook as useFetch
  participant Clerk as Clerk SignIn
  participant API as FAPI

  UI->>Hook: trigger fetch()
  Hook->>Clerk: signIn.prepareFirstFactor(factor)
  Clerk->>API: POST /prepare_first_factor
  API-->>Clerk: 200 OK / Error
  alt success
    Clerk-->>Hook: result
    Hook-->>UI: onSuccess(result)
    UI->>UI: props.onFactorPrepare()
  else error
    Clerk-->>Hook: Error
    Hook->>Hook: set error state
    Hook-->>UI: onError(error)
    UI->>UI: handleError(error, [], card.setError)
  end
Loading
sequenceDiagram
  autonumber
  participant UI as SignUpEmail/PhoneCodeCard
  participant Hook as useFetch
  participant Clerk as Clerk SignUp
  participant API as FAPI

  UI->>Hook: trigger fetch()
  Hook->>Clerk: prepareEmail/PhoneVerification(...)
  Clerk->>API: POST /prepare_verification
  API-->>Clerk: 200 OK / Error
  alt success
    Clerk-->>Hook: result
    Hook-->>UI: onSuccess(result)
  else error
    Clerk-->>Hook: Error
    Hook->>Hook: set error state
    Hook-->>UI: onError(error)
    UI->>UI: handleError(error, [], card.setError)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Ensure SignIn sends prepare on repeated attempts with same factor (USER-3157)

"A rabbit taps the keys tonight,
prepares run true, no stale invite.
Fresh codes hop in, errors are caught—
I nibble bugs and ship the lot. 🐇✨"

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch elef/USER-3157

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

Other keywords and placeholders

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

Status, Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
.changeset/crazy-days-tan.md (1)

5-5: Nit: Polish wording and capitalization (“OTP”), drop quotes.

Clearer, grammatically correct, and consistent with product terminology.

-Fixes issue where "prepare" API request would only fire once, preventing end users from receiving fresh otp codes.
+Fixes a bug where the prepare API request fired only once, preventing end users from receiving fresh OTP codes.
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1)

27-27: Centralized error handling looks good; consider a more specific cache “name”.

To reduce chances of cross-feature cache collisions, make the name param explicit.

-    {
-      name: 'prepare',
+    {
+      name: 'signUp.prepareEmailAddressVerification',
       strategy: 'email_code',
       number: signUp.emailAddress,
     },

Also applies to: 35-35

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

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

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9796fbf and cbca675.

📒 Files selected for processing (5)
  • .changeset/crazy-days-tan.md (1 hunks)
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx (1 hunks)
  • packages/clerk-js/src/ui/hooks/useFetch.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
packages/clerk-js/src/ui/**/*.{ts,tsx}

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

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

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.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/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.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/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.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/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.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/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.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/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.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/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.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/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/crazy-days-tan.md
🧬 Code graph analysis (3)
packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx (2)
packages/clerk-js/src/ui/hooks/useFetch.ts (1)
  • useFetch (85-188)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (69-91)
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (69-91)
packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx (1)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (69-91)
🪛 LanguageTool
.changeset/crazy-days-tan.md

[grammar] ~5-~5: There might be a mistake here.
Context: ...nd users from receiving fresh otp codes.

(QB_NEW_EN)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
packages/clerk-js/src/ui/hooks/useFetch.ts (1)

91-93: Type onError callback and catch parameter as unknown

Aligns with our TS guidelines; verified no useFetch callers return void, so this change is safe.

packages/clerk-js/src/ui/hooks/useFetch.ts
@@ -91,7 +91,7
-    onError?: (error: Error) => void;
+    onError?: (error: unknown) => void;
@@ -170,7 +170,7
-      .catch((e: Error) => {
+      .catch((e: unknown) => {
packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx (1)

85-89: Good fix: fetcher now returns a Promise; cache semantics restored.

Returning signIn.prepareFirstFactor(...) allows useFetch to manage cache and callbacks correctly. Error handling is centralized via onError, and onSuccess hooks into onFactorPrepare()—nice.

packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx (1)

39-39: Fetcher returns a Promise and errors are centralized.

Switching to a direct Promise-returning fetcher and moving errors to onError matches the new pattern and prevents the “fires once” bug.

Also applies to: 47-47

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

Caution

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

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

16-23: Propagate the caught error in VerifyDomainForm to match the caching contract
In packages/clerk-js/src/ui/components/OrganizationProfile/VerifyDomainForm.tsx, the catch on prepareAffiliationVerification must return the error:

- domain?.prepareAffiliationVerification({ affiliationEmailAddress: emailField.value }).catch(err => {
-   handleError(err, [emailField], card.setError);
- });
+ domain?.prepareAffiliationVerification({ affiliationEmailAddress: emailField.value }).catch(err => {
+   handleError(err, [emailField], card.setError);
+   return err;
+ });
🧹 Nitpick comments (2)
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (2)

30-33: Good: resolve with the error object to keep the promise observable and cached

Catching, handling, and returning the error here aligns with the goal of not skipping subsequent prepares. Consider centralizing error handling via useFetch’s onError to avoid embedding error logic in the fetcher.

-      : () =>
-          signUp.prepareEmailAddressVerification({ strategy: 'email_code' }).catch(err => {
-            handleError(err, [], card.setError);
-            return err;
-          }),
+      : () => signUp.prepareEmailAddressVerification({ strategy: 'email_code' }),
 ...
-    {
-      staleTime: 100,
-    },
+    {
+      staleTime: 100,
+      onError: err => handleError(err, [], card.setError),
+    },

If the cache relies on resolved promises only, keep the current approach. Otherwise, delegating to onError simplifies the fetcher.


40-41: Nit: Document or lift staleTime=100 to a named constant

100ms is very short for network-bound ops and easy to misinterpret. Consider a named constant or a short comment on why this value is chosen.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

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

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between cbca675 and e9bdff4.

📒 Files selected for processing (3)
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx
🧰 Additional context used
📓 Path-based instructions (9)
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/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpEmailCodeCard.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpEmailCodeCard.tsx
🧬 Code graph analysis (1)
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (69-91)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx (1)

39-39: Align fetcher args with prepare() for clarity

Since we already gate on isAlternativePhoneCodeProvider, you can pass channelToBeSent here for symmetry with prepare(). This reduces cognitive load and makes future changes safer.

-      : () => signUp.preparePhoneNumberVerification({ strategy: 'phone_code', channel: undefined }),
+      : () => signUp.preparePhoneNumberVerification({ strategy: 'phone_code', channel: channelToBeSent }),
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1)

27-32: Use a descriptive, unique name for the query key

name: 'prepare' is generic and may collide logically with other prepares. Prefer a fully qualified, operation-scoped name for clearer debugging and safer caching.

-    {
-      name: 'prepare',
+    {
+      name: 'signUp.prepareEmailAddressVerification',
       strategy: 'email_code',
       number: signUp.emailAddress,
     },
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

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

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e9bdff4 and 487158c.

📒 Files selected for processing (4)
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1 hunks)
  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx (1 hunks)
  • packages/clerk-js/src/ui/hooks/useFetch.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/clerk-js/src/ui/hooks/useFetch.ts
  • packages/clerk-js/src/ui/components/SignIn/SignInFactorOneCodeForm.tsx
🧰 Additional context used
📓 Path-based instructions (9)
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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.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/SignUp/SignUpPhoneCodeCard.tsx
  • packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
🧬 Code graph analysis (2)
packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx (1)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (69-91)
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1)
packages/clerk-js/src/ui/utils/errorHandler.ts (1)
  • handleError (69-91)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx (1)

27-27: LGTM: moved error handling to useFetch.onError

Dropping the inline .catch from the fetcher and delegating to onError is the right direction.

Comment on lines 34 to 36
staleTime: 100,
onError: err => handleError(err, [], card.setError),
},
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify onError safety with handleError rethrows; double-check staleTime

Same concern as the phone code card: confirm useFetch won’t surface unhandled exceptions if handleError rethrows, and that staleTime: 100 meets the intended dedupe window.

Run:

Expected:

  • onError invocation cannot crash the component tree.
  • Comment or test validates the 100ms window is sufficient for “prepare fires once” semantics.

🏁 Script executed:

#!/bin/bash
# Confirm try/catch around user-provided onError and the internal error flow
rg -nP -C3 'onError\s*\(|try|catch|setState' packages/clerk-js/src/ui/hooks/useFetch.ts

Length of output: 285


🏁 Script executed:

#!/bin/bash
# Inspect the beginning of the useFetch hook to locate onError invocation
sed -n '1,200p' packages/clerk-js/src/ui/hooks/useFetch.ts

Length of output: 5357


🏁 Script executed:

#!/bin/bash
# Inspect the SignUpEmailCodeCard and SignUpPhoneCodeCard for staleTime and onError usage
sed -n '1,200p' packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx
echo "---"
sed -n '1,200p' packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx

Length of output: 5735


🏁 Script executed:

#!/bin/bash
rg -n "export (function|const) handleError" -n packages/clerk-js/src/ui/utils

Length of output: 209


Ensure onError callback safety and clarify staleTime usage

  • In useFetch (packages/clerk-js/src/ui/hooks/useFetch.ts), wrap the options.onError?.(e) invocation in a try/catch to prevent unhandled promise rejections if handleError throws.
  • Add a code comment or unit test to verify that the 100 ms staleTime (in SignUpEmailCodeCard.tsx and SignUpPhoneCodeCard.tsx) provides the intended dedupe window for “prepare fires once” semantics.
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/SignUp/SignUpEmailCodeCard.tsx around
lines 34-36, the options passed to useFetch set staleTime: 100 and onError: err
=> handleError(err, [], card.setError); update two things: in
packages/clerk-js/src/ui/hooks/useFetch.ts wrap the invocation of
options.onError?.(e) in a try/catch and log or swallow any errors to prevent
unhandled promise rejections if the provided handler (e.g., handleError) throws;
and in SignUpEmailCodeCard.tsx (and SignUpPhoneCodeCard.tsx) add a concise code
comment next to staleTime: 100 explaining that this 100ms window is the intended
de-duplication/deduping window for “prepare fires once” semantics or add a unit
test asserting that preparing twice within 100ms only triggers a single prepare
call.

Comment on lines 46 to 48
staleTime: 100,
onError: err => handleError(err, [], card.setError),
},
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify onError behavior with handleError rethrows; confirm staleTime=100ms is intentional

handleError rethrows unknown errors. Ensure useFetch guards against exceptions thrown inside onError so we don’t crash render. Also, validate that staleTime: 100 sufficiently dedupes initial rerenders without suppressing legitimate retries.

Run:

Expected:

  • useFetch calls onError inside a try/catch or otherwise prevents rethrow from breaking React render.
  • staleTime choice is deliberate (doc or comment) to coalesce only immediate duplicate prepares.

🏁 Script executed:

#!/bin/bash
# Inspect onError invocation and error propagation in useFetch
rg -nP -C3 'function\s+useFetch|\bonError\b|\bcatch\s*\(' packages/clerk-js/src/ui/hooks/useFetch.ts

# Scan all useFetch callers for very short staleTime and generic names that could collide
rg -nP -C1 'useFetch\(' packages | sed -n '1,200p'

Length of output: 5044


🏁 Script executed:

#!/bin/bash
# Search for handleError definition and usage across clerk-js
rg -nR 'handleError' -n packages/clerk-js

Length of output: 446


🏁 Script executed:

#!/bin/bash
# Show useFetch implementation including error invocation context
rg -nP -C10 'function\s+useFetch' packages/clerk-js/src/ui/hooks/useFetch.ts
rg -nP -C10 '\.catch' packages/clerk-js/src/ui/hooks/useFetch.ts

# Show import and usage of handleError in SignUpPhoneCodeCard
sed -n '1,50p' packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx

# Search for handleError definition across the repo
rg -n 'handleError' -n .

Length of output: 25854


🏁 Script executed:

#!/bin/bash
# Inspect staleTime handling in useFetch
rg -nP -C5 'staleTime' packages/clerk-js/src/ui/hooks/useFetch.ts

Length of output: 1310


🏁 Script executed:

#!/bin/bash
rg -nP -C10 'export const handleError' packages/clerk-js/src/ui/utils/errorHandler.ts

Length of output: 644


Guard onError invocation and confirm staleTime override

  • Wrap options.onError(e) in a try/catch inside useFetch’s .catch handler (packages/clerk-js/src/ui/hooks/useFetch.ts ~L170); since handleError can rethrow unknown errors, unhandled promise rejections may occur.
  • The 100 ms staleTime override matches other prepare hooks (e.g. SignInFactorOneCodeForm) and is intentional to dedupe rapid remounts without impacting legitimate retries.
🤖 Prompt for AI Agents
In packages/clerk-js/src/ui/components/SignUp/SignUpPhoneCodeCard.tsx around
lines 46-48, guard the onError invocation by wrapping options.onError(e) in a
try/catch inside the useFetch .catch handler so any error thrown by handleError
(or other callbacks) does not create an unhandled promise rejection; if the
callback throws, catch it and log or forward to card.setError as a fallback.
Leave the staleTime: 100 override as-is (it is intentional to dedupe rapid
remounts).

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx (4)

26-28: Tighten types for render helper to avoid any.

Use the render signature to type options and prefer JSX.Element over React.ReactElement to avoid importing React types.

-  const renderWithProviders = (component: React.ReactElement, options?: any) => {
+  const renderWithProviders = (
+    component: JSX.Element,
+    options?: Parameters<typeof render>[1],
+  ) => {

124-127: Consider asserting the presence of the new callbacks in this scenario too.

To keep expectations consistent across scenarios, also validate onSuccess/onError (and staleTime) here.

-expect(vi.mocked(useFetch)).toHaveBeenCalledWith(expect.any(Function), expect.any(Object), expect.any(Object));
+expect(vi.mocked(useFetch)).toHaveBeenCalledWith(
+  expect.any(Function),
+  expect.any(Object),
+  expect.objectContaining({
+    staleTime: 100,
+    onSuccess: expect.any(Function),
+    onError: expect.any(Function),
+  }),
+);

144-148: Apply the same options assertion for consistency.

-  expect(vi.mocked(useFetch)).toHaveBeenCalledWith(
-    expect.any(Function), // fetcher should still be a function because shouldAvoidPrepare requires BOTH conditions
-    expect.any(Object),
-    expect.any(Object),
-  );
+  expect(vi.mocked(useFetch)).toHaveBeenCalledWith(
+    expect.any(Function), // fetcher should still be a function because shouldAvoidPrepare requires BOTH conditions
+    expect.any(Object),
+    expect.objectContaining({
+      staleTime: 100,
+      onSuccess: expect.any(Function),
+      onError: expect.any(Function),
+    }),
+  );

164-168: And here, to cover the non-prepared path as well.

-  expect(vi.mocked(useFetch)).toHaveBeenCalledWith(
-    expect.any(Function), // fetcher should be a function when prepare is allowed
-    expect.any(Object),
-    expect.any(Object),
-  );
+  expect(vi.mocked(useFetch)).toHaveBeenCalledWith(
+    expect.any(Function), // fetcher should be a function when prepare is allowed
+    expect.any(Object),
+    expect.objectContaining({
+      staleTime: 100,
+      onSuccess: expect.any(Function),
+      onError: expect.any(Function),
+    }),
+  );
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

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

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 487158c and 51340a1.

📒 Files selected for processing (1)
  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx (2 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
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/SignIn/__tests__/SignInFactorOneCodeForm.spec.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/SignIn/__tests__/SignInFactorOneCodeForm.spec.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/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.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/SignIn/__tests__/SignInFactorOneCodeForm.spec.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/SignIn/__tests__/SignInFactorOneCodeForm.spec.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/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}

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

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

Files:

  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.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/SignIn/__tests__/SignInFactorOneCodeForm.spec.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/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx
**/__tests__/**/*.{ts,tsx}

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

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

Files:

  • packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (2)
packages/clerk-js/src/ui/components/SignIn/__tests__/SignInFactorOneCodeForm.spec.tsx (2)

59-63: Good: options assertion made future-proof and verifies the new callbacks.

Using expect.objectContaining with staleTime and the onSuccess/onError callbacks is the right contract check for useFetch here.


96-100: Good: cache key with channel + robust options assertion.

Matching the WhatsApp channel in factorKey and asserting onSuccess/onError presence looks correct and aligns with the new error handling path.

Copy link
Member

@jacekradko jacekradko left a comment

Choose a reason for hiding this comment

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

Confirmed it solves the issue. Thanks @panteliselef! 🚀

@panteliselef panteliselef merged commit 73fe6ff into main Sep 3, 2025
39 checks passed
@panteliselef panteliselef deleted the elef/USER-3157 branch September 3, 2025 20:14
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