Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Nov 3, 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

  • Bug Fixes

    • Improved initialization reliability with automatic retry logic for transient failures, network errors, and dev-browser authentication scenarios
    • Enhanced error handling with better error context propagation via cause chains
    • Added graceful degradation using cached snapshots during fetch failures
  • Tests

    • Added comprehensive test coverage for initialization retry behavior and various error scenarios

@changeset-bot
Copy link

changeset-bot bot commented Nov 3, 2025

⚠️ No Changeset found

Latest commit: aec61e8

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

This PR includes no changesets

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

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

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

@vercel
Copy link

vercel bot commented Nov 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 Nov 3, 2025 1:37am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 3, 2025

Walkthrough

This PR introduces a new retry utility with exponential backoff and jitter, refactors the Clerk initialization flow to leverage retry logic for resilience against transient failures, updates error handling to propagate root causes, and adds comprehensive tests for both retry behavior and initialization recovery scenarios.

Changes

Cohort / File(s) Summary
Retry utility implementation
packages/clerk-js/src/utils/retry.ts
New retry utility with exponential backoff and optional jitter; supports configurable max attempts and async shouldRetry predicate
Retry utility tests
packages/clerk-js/src/utils/__tests__/retry.test.ts
Test suite validating retry logic, backoff calculations, async predicates, and exhaustion scenarios
Initialization refactoring
packages/clerk-js/src/core/clerk.ts
Refactored load path to wrap initialization with retry utility; splits environment and client initialization; adds degraded initialization fallback and dev-browser authentication handling
Error handling updates
packages/clerk-js/src/core/errors.ts
Updated clerkErrorInitFailed to accept optional error parameter and propagate it as Error cause
Initialization tests
packages/clerk-js/src/core/__tests__/clerk.test.ts
New test blocks for load retry behavior, network error handling, and error propagation verification
Build configuration
packages/clerk-js/tsconfig.json
Added es2022.error to compiler lib options

Sequence Diagram(s)

sequenceDiagram
    participant App as Application
    participant Clerk as Clerk.load()
    participant Retry as withRetry wrapper
    participant Init as initializeClerk
    participant Env as Environment API
    participant Client as Client API
    
    App->>Clerk: load()
    Clerk->>Retry: invoke(maxAttempts: 2, jitter: true)
    loop Retry Attempts
        Retry->>Init: execute attempt
        Init->>Env: fetch/update environment
        alt Env Success
            Env-->>Init: environment data
            Init->>Client: fetch/update client
            alt Client Success
                Client-->>Init: client data
                Init-->>Retry: success ✓
                Note over Retry: Ready state reached
            else 4xx Client Error
                Client-->>Init: error
                Init-->>Retry: throw (no retry)
            else Network Error
                Client-->>Init: error
                Init-->>Retry: error (check shouldRetry)
            end
        else Fetch Failed
            Env-->>Init: error
            Init->>Env: use cached snapshot
            Init->>Client: attempt with cached env
            Init-->>Retry: error or retry
        end
        alt shouldRetry: true & attempt < maxAttempts
            Retry->>Retry: calculate backoff with jitter
            Retry->>Retry: sleep(backoff)
        else shouldRetry: false or final attempt
            Retry-->>Clerk: throw error
            Clerk-->>App: initialization failed
        end
    end
    Retry-->>Clerk: initialization succeeded
    Clerk->>Clerk: mount components, set ready
    Clerk-->>App: ready
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • packages/clerk-js/src/core/clerk.ts: Dense refactoring of initialization logic with multiple error handling paths, retry integration, and degraded initialization scenarios—requires careful verification of flow control and state transitions.
  • packages/clerk-js/src/utils/retry.ts: New utility with exponential backoff and jitter logic; verify edge cases and backoff calculations align with production expectations.
  • packages/clerk-js/src/core/tests/clerk.test.ts: Complex test scenarios involving mock state management, timer behavior, and error propagation chains—verify test assertions comprehensively cover retry and recovery paths.
  • packages/clerk-js/src/utils/tests/retry.test.ts: Async predicate handling and fake timer integration; ensure all backoff and jitter scenarios are properly validated.

Poem

🐰 A hop, a skip, a retry bound,
With exponential backoff round and round,
When networks falter, we bounce back with grace,
Jitter in hand, we finish the race!
Errors now carry their cause with such care,
The Clerk initialization's beyond all compare.

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "fix(clerk-js): Correct init retry logic [WIP]" is directly related to the main changes in the pull request. The changeset introduces a new withRetry utility function, refactors the initialization flow in clerk.ts to use this retry mechanism, enhances error handling to include error causes, and adds comprehensive tests for the retry behavior. The title accurately captures the primary focus of these changes—implementing and correcting the initialization retry logic. The title is concise, uses proper conventional commit formatting, and provides enough specificity for developers scanning history to understand the purpose of the changes.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/init-retry-logic

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 3, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: aec61e8

@blacksmith-sh
Copy link

blacksmith-sh bot commented Nov 3, 2025

Found 4 test failures on Blacksmith runners:

Test View Logs
[chrome] › integration/tests/
components.test.ts:102:9 › component smoke tests @generic › long-running--next.appRoute
r.withEmailCodes › OrganizationProfile supports fallback
View Logs
[chrome] › integration/tests/
components.test.ts:102:9 › component smoke tests @generic › long-running--next.appRoute
r.withEmailCodes › UserButton supports fallback
View Logs
[chrome] › integration/tests/
resiliency.test.ts:87:7 › resiliency @generic › long-running--react.vite.withEmailCodes
› resiliency to not break devBrowser - dummy client and is not created on /</code><br /><code>client 4xx errors
View Logs
[chrome] › integration/tests/
session-tasks-multi-session.test.ts:33:9 › session tasks multi-session flow @nextjs › l
ong-running--next.appRouter.withSessionTasks › when switching sessions, navigate to tas
k
View Logs


Fix in Cursor

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

📜 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 f47b5a3 and aec61e8.

📒 Files selected for processing (6)
  • packages/clerk-js/src/core/__tests__/clerk.test.ts (3 hunks)
  • packages/clerk-js/src/core/clerk.ts (2 hunks)
  • packages/clerk-js/src/core/errors.ts (1 hunks)
  • packages/clerk-js/src/utils/__tests__/retry.test.ts (1 hunks)
  • packages/clerk-js/src/utils/retry.ts (1 hunks)
  • packages/clerk-js/tsconfig.json (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/clerk-js/src/core/errors.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/clerk-js/src/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/utils/retry.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

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

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/errors.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/clerk-js/src/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/utils/retry.ts
  • packages/clerk-js/tsconfig.json
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/errors.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/clerk-js/src/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/utils/retry.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
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/core/errors.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/clerk-js/src/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/utils/retry.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
**/*.{ts,tsx}

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

Use proper TypeScript error types

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

Files:

  • packages/clerk-js/src/core/errors.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/clerk-js/src/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/utils/retry.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
**/*.{js,ts,tsx,jsx}

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

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

Files:

  • packages/clerk-js/src/core/errors.ts
  • packages/clerk-js/src/core/clerk.ts
  • packages/clerk-js/src/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/utils/retry.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
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/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
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/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.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/clerk-js/src/utils/__tests__/retry.test.ts
  • packages/clerk-js/src/core/__tests__/clerk.test.ts
packages/*/tsconfig.json

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

Type checking must be performed with TypeScript and publint.

Files:

  • packages/clerk-js/tsconfig.json
🧬 Code graph analysis (3)
packages/clerk-js/src/core/clerk.ts (7)
packages/clerk-js/src/core/resources/Environment.ts (1)
  • Environment (17-100)
packages/clerk-js/src/utils/localStorage.ts (1)
  • SafeLocalStorage (17-68)
packages/shared/src/errors/helpers.ts (3)
  • is4xxError (33-36)
  • isNetworkError (43-47)
  • isClerkRuntimeError (83-85)
packages/clerk-js/src/core/jwt-client.ts (1)
  • createClientFromJwt (19-100)
packages/clerk-js/src/utils/errors.ts (1)
  • isError (4-6)
packages/clerk-js/src/utils/retry.ts (1)
  • withRetry (19-46)
packages/clerk-js/src/core/errors.ts (1)
  • clerkErrorInitFailed (19-21)
packages/clerk-js/src/utils/__tests__/retry.test.ts (1)
packages/clerk-js/src/utils/retry.ts (1)
  • withRetry (19-46)
packages/clerk-js/src/core/__tests__/clerk.test.ts (2)
packages/clerk-js/src/core/clerk.ts (1)
  • Clerk (198-2989)
packages/clerk-js/src/core/auth/AuthCookieService.ts (1)
  • AuthCookieService (40-255)
⏰ 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). (28)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Static analysis
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/tsconfig.json (1)

10-10: Cause-enabled lib entry looks good

Adding es2022.error keeps the compiler aware of Error options with cause, aligning tsconfig with the new error handling.

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

19-21: Wrapping the init failure with a cause is spot on

Passing the underlying error as cause sharpens debugging and meshes with the retry utilities.

packages/clerk-js/src/utils/__tests__/retry.test.ts (1)

1-156: Great coverage on retry behavior

The suite nails first-try success, retry gating, async predicates, and backoff timing—including jitter—so regressions here should be caught quickly.

packages/clerk-js/src/core/__tests__/clerk.test.ts (1)

1-282: Retry regression tests read well

The new fixtures and expectations around dev-browser recovery and network error propagation exercise the retry path end-to-end, which should keep future init changes safe.

Comment on lines +2575 to +2588
const initEnvironmentPromise = Environment.getInstance()
.fetch({ touch: shouldTouchEnv })
.then(res => this.updateEnvironment(res))
.catch(() => {
++initializationDegradedCounter;
const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>(
CLERK_ENVIRONMENT_STORAGE_ENTRY,
null,
);

try {
const initEnvironmentPromise = Environment.getInstance()
.fetch({ touch: shouldTouchEnv })
.then(res => this.updateEnvironment(res))
.catch(() => {
++initializationDegradedCounter;
const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>(
CLERK_ENVIRONMENT_STORAGE_ENTRY,
null,
);
if (environmentSnapshot) {
this.updateEnvironment(new Environment(environmentSnapshot));
}
});
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 swallow the environment fetch failure when no cache exists.
When the very first /environment request fails (e.g., transient network blip on a cold start), this catch clause increments the degraded counter, finds no snapshot in localStorage, and then resolves. Because the error never bubbles out, withRetry treats the attempt as a success and skips the second pass, so load() completes with this.environment still holding the empty singleton. That leaves the UI without required config until the user hard refreshes. Please rethrow when we can’t hydrate from cache so the retry wrapper can actually run:

-        .catch(() => {
+        .catch(error => {
           ++initializationDegradedCounter;
           const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>(
             CLERK_ENVIRONMENT_STORAGE_ENTRY,
             null,
           );

           if (environmentSnapshot) {
             this.updateEnvironment(new Environment(environmentSnapshot));
+            return;
           }
+
+          throw error;
         });
📝 Committable suggestion

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

Suggested change
const initEnvironmentPromise = Environment.getInstance()
.fetch({ touch: shouldTouchEnv })
.then(res => this.updateEnvironment(res))
.catch(() => {
++initializationDegradedCounter;
const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>(
CLERK_ENVIRONMENT_STORAGE_ENTRY,
null,
);
try {
const initEnvironmentPromise = Environment.getInstance()
.fetch({ touch: shouldTouchEnv })
.then(res => this.updateEnvironment(res))
.catch(() => {
++initializationDegradedCounter;
const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>(
CLERK_ENVIRONMENT_STORAGE_ENTRY,
null,
);
if (environmentSnapshot) {
this.updateEnvironment(new Environment(environmentSnapshot));
}
});
const initEnvironmentPromise = Environment.getInstance()
.fetch({ touch: shouldTouchEnv })
.then(res => this.updateEnvironment(res))
.catch(error => {
+initializationDegradedCounter;
const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>(
CLERK_ENVIRONMENT_STORAGE_ENTRY,
null,
);
if (environmentSnapshot) {
this.updateEnvironment(new Environment(environmentSnapshot));
return;
}
throw error;
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/clerk.ts around lines 2575 to 2588, the catch
block for Environment.getInstance().fetch currently swallows errors when no
cached snapshot exists causing withRetry to think the attempt succeeded; change
the catch to receive the error (catch(err)) and after incrementing
initializationDegradedCounter and attempting to read the local snapshot, if no
snapshot is found rethrow the original error (or wrap and throw it) so the retry
wrapper can run; if a snapshot exists, continue to hydrate environment as before
and do not rethrow.

Comment on lines +19 to +45
export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T> {
let lastError: unknown;

for (let attempt = 0; attempt < options.maxAttempts; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;

const shouldRetry = await Promise.resolve(options.shouldRetry(error));

if (!shouldRetry) {
throw error;
}

const isLastAttempt = attempt === options.maxAttempts - 1;

if (isLastAttempt) {
throw error;
}

const backoffMs = calculateBackoff(attempt, options.jitter ?? true);
await sleep(backoffMs);
}
}

throw lastError;
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

Guard against zero maxAttempts before looping

If a caller passes maxAttempts = 0, the loop body never runs, lastError stays undefined, and the final throw lastError ends up throwing undefined, masking the configuration bug. Adding an upfront guard keeps the failure explicit and avoids throwing a useless value.

-export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T> {
-  let lastError: unknown;
+export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T> {
+  if (options.maxAttempts < 1) {
+    throw new Error('withRetry requires maxAttempts to be at least 1');
+  }
+
+  let lastError: unknown;
🤖 Prompt for AI Agents
In packages/clerk-js/src/utils/retry.ts around lines 19 to 45, the function can
throw undefined when options.maxAttempts is 0 because the loop never runs and
lastError stays undefined; add an upfront guard that validates
options.maxAttempts is a positive integer (e.g., if
(!Number.isInteger(options.maxAttempts) || options.maxAttempts <= 0) throw new
Error("withRetry: maxAttempts must be a positive integer")), so callers get a
clear, immediate error instead of throwing undefined.

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.

3 participants