Skip to content

Conversation

brkalow
Copy link
Member

@brkalow brkalow commented Sep 26, 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
    • Resolves intermittent failures when loading the Clerk script by detecting failed requests, removing problematic scripts, and retrying automatically.
    • Prevents stalls during initialization by cleaning up stale scripts on timeout and attempting a clean reload.
  • Refactor
    • Streamlines script loading and retry logic for more robust startup behavior.
  • Documentation
    • Clarifies comments to reflect improved error detection and automatic retry behavior, aiding maintainability.

Copy link

changeset-bot bot commented Sep 26, 2025

⚠️ No Changeset found

Latest commit: 6b3efd1

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

This PR includes no changesets

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

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

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

Copy link

vercel bot commented Sep 26, 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 26, 2025 8:49pm

Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

Walkthrough

Implements error detection for existing Clerk script loads using the Performance API, adds cleanup and retry logic when failures or timeouts occur, and unifies URL handling. The loader now removes errored or timed-out existing scripts before attempting a fresh load, relying on existing loadScript retry behavior for new scripts.

Changes

Cohort / File(s) Summary of changes
Clerk JS loader resilience
packages/shared/src/loadClerkJsScript.ts
Adds hasScriptRequestError(scriptUrl) using Performance API; updates loadClerkJsScript to detect failures for existing scripts, wait-with-timeout for Clerk readiness, and remove/retry on error or timeout; refines comments/JSDoc; consolidates URL handling via scriptUrl.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant App
  participant Loader as loadClerkJsScript
  participant Perf as Performance API
  participant DOM as Document
  participant Clerk as window.Clerk
  participant Net as Network

  App->>Loader: loadClerkJsScript(options)
  Loader->>DOM: Find existing <script src=scriptUrl?>
  alt Existing script found
    Loader->>Perf: hasScriptRequestError(scriptUrl)
    alt Error detected
      Loader->>DOM: Remove existing <script>
      note right of Loader: Cleanup before retry
      Loader->>Net: Load new script (loadScript with built-in retries)
      Net-->>DOM: Inject new <script>
      DOM-->>Clerk: Initialize
      Loader-->>App: Resolve when Clerk ready
    else No error detected
      Loader->>Clerk: Wait until Clerk ready (timeout)
      alt Ready before timeout
        Loader-->>App: Resolve
      else Timeout
        Loader->>DOM: Remove existing <script>
        note right of Loader: Retry with a fresh load
        Loader->>Net: Load new script (loadScript retries)
        Net-->>DOM: Inject new <script>
        DOM-->>Clerk: Initialize
        Loader-->>App: Resolve when Clerk ready
      end
    end
  else No existing script
    Loader->>Net: Load new script (loadScript retries)
    Net-->>DOM: Inject new <script>
    DOM-->>Clerk: Initialize
    Loader-->>App: Resolve when Clerk ready
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

I nudge the moonlit scripts to run,
If they stumble, one by one—undone.
I sweep the tag, reset the night,
Then hop and fetch a fresher light.
With patient paws and tidy flair,
I make Clerk load from midnight air. 🐇✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly and accurately describes the primary change, highlighting the addition of intelligent retry logic for existing Clerk JS scripts in the shared package while following the conventional commit format.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch brk.feat/clerk-js-retry

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

* @param scriptUrl - The URL of the script to check.
* @returns True if the script has failed to load due to a network/HTTP error.
*/
function hasScriptRequestError(scriptUrl: string): boolean {
Copy link
Member Author

Choose a reason for hiding this comment

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

This is a slightly cursed way trying to check for an existing script load error without the ability to add an onError callback to the script. window.performance.getEntries() should contain the network request to fetch clerk-js, and so we can better infer what the status is without an arbitrary timeout.

Copy link
Member

Choose a reason for hiding this comment

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

I like this!

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

Caution

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

⚠️ Outside diff range comments (1)
packages/shared/src/loadClerkJsScript.ts (1)

209-216: Avoid unhandled promise rejection from detached catch

Throwing inside the detached catch creates an unhandledrejection. Let the timeout path reject instead.

-  }).catch(() => {
-    throw new Error(FAILED_TO_LOAD_ERROR);
-  });
+  }).catch(() => {
+    // Let waitForClerkWithTimeout handle rejection; avoid unhandled promise rejection here.
+  });
🧹 Nitpick comments (1)
packages/shared/src/loadClerkJsScript.ts (1)

145-153: Initialize poll interval before first check (tiny cleanup)

Define pollInterval before calling checkAndResolve to avoid passing undefined to cleanup.

-  checkAndResolve();
-
-  const pollInterval = setInterval(() => {
+  const pollInterval = setInterval(() => {
     if (resolved) {
       clearInterval(pollInterval);
       return;
     }
     checkAndResolve();
   }, 100);
+  checkAndResolve();
📜 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 8e8bfb5 and 6b3efd1.

📒 Files selected for processing (1)
  • packages/shared/src/loadClerkJsScript.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/loadClerkJsScript.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/shared/src/loadClerkJsScript.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/loadClerkJsScript.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/shared/src/loadClerkJsScript.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/shared/src/loadClerkJsScript.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/shared/src/loadClerkJsScript.ts
🧬 Code graph analysis (1)
packages/shared/src/loadClerkJsScript.ts (1)
packages/shared/src/loadScript.ts (1)
  • loadScript (14-53)
🔇 Additional comments (1)
packages/shared/src/loadClerkJsScript.ts (1)

192-206: Detect Clerk script by src with SSR guard

Replace the old selector with a src‐based lookup and SSR guard, falling back to known data attributes:

-  const existingScript = document.querySelector<HTMLScriptElement>('script[data-clerk-js-script]');
+  const existingScript =
+    typeof document !== 'undefined'
+      ? document.querySelector<HTMLScriptElement>(`script[src="${scriptUrl}"]`) ??
+        document.querySelector<HTMLScriptElement>(
+          'script[data-clerk-publishable-key],script[data-clerk-frontend-api],script[data-clerk-domain],script[data-clerk-proxy-url]'
+        )
+      : null;

Then use const existingSrc = existingScript.src || scriptUrl in the hasScriptRequestError(existingSrc) check.

Verify that data-clerk-js-script isn’t referenced anywhere in code, docs, or examples before removing it.

Comment on lines +62 to +98
/**
* Checks if an existing script has a request error using Performance API.
*
* @param scriptUrl - The URL of the script to check.
* @returns True if the script has failed to load due to a network/HTTP error.
*/
function hasScriptRequestError(scriptUrl: string): boolean {
if (typeof window === 'undefined' || !window.performance) {
return false;
}

const entries = performance.getEntries() as PerformanceResourceTiming[];
const scriptEntry = entries.find(entry => entry.name === scriptUrl);

if (!scriptEntry) {
return false;
}

// transferSize === 0 with responseEnd === 0 indicates network failure
// transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request
if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {
// If there was no response at all, it's definitely an error
if (scriptEntry.responseEnd === 0) {
return true;
}
// If we got a response but no content, likely an HTTP error (4xx/5xx)
if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {
return true;
}

if (scriptEntry.responseStatus === 0) {
return true;
}
}

return false;
}
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 | 🔴 Critical

Fix TS type error and reduce false positives in Performance heuristics

  • responseStatus is not part of PerformanceResourceTiming; this breaks TS.
  • transferSize/decodedBodySize being 0 is common for cross-origin without TAO and is not an error signal by itself.

Refactor to use getEntriesByName and only treat the “no response observed” case as failure.

-function hasScriptRequestError(scriptUrl: string): boolean {
-  if (typeof window === 'undefined' || !window.performance) {
-    return false;
-  }
-
-  const entries = performance.getEntries() as PerformanceResourceTiming[];
-  const scriptEntry = entries.find(entry => entry.name === scriptUrl);
-
-  if (!scriptEntry) {
-    return false;
-  }
-
-  // transferSize === 0 with responseEnd === 0 indicates network failure
-  // transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request
-  if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {
-    // If there was no response at all, it's definitely an error
-    if (scriptEntry.responseEnd === 0) {
-      return true;
-    }
-    // If we got a response but no content, likely an HTTP error (4xx/5xx)
-    if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {
-      return true;
-    }
-
-    if (scriptEntry.responseStatus === 0) {
-      return true;
-    }
-  }
-
-  return false;
-}
+function hasScriptRequestError(scriptUrl: string): boolean {
+  if (typeof window === 'undefined' || !('performance' in window)) {
+    return false;
+  }
+  const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceEntry[];
+  const scriptEntry = entries.find((e): e is PerformanceResourceTiming => {
+    return (e as PerformanceResourceTiming).entryType === 'resource';
+  });
+  if (!scriptEntry) {
+    return false;
+  }
+  // Clear-cut failure: no response observed. Sizes may be 0 cross-origin even on success (no TAO).
+  return scriptEntry.responseEnd === 0;
+}
📝 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
/**
* Checks if an existing script has a request error using Performance API.
*
* @param scriptUrl - The URL of the script to check.
* @returns True if the script has failed to load due to a network/HTTP error.
*/
function hasScriptRequestError(scriptUrl: string): boolean {
if (typeof window === 'undefined' || !window.performance) {
return false;
}
const entries = performance.getEntries() as PerformanceResourceTiming[];
const scriptEntry = entries.find(entry => entry.name === scriptUrl);
if (!scriptEntry) {
return false;
}
// transferSize === 0 with responseEnd === 0 indicates network failure
// transferSize === 0 with responseEnd > 0 might be a 4xx/5xx error or blocked request
if (scriptEntry.transferSize === 0 && scriptEntry.decodedBodySize === 0) {
// If there was no response at all, it's definitely an error
if (scriptEntry.responseEnd === 0) {
return true;
}
// If we got a response but no content, likely an HTTP error (4xx/5xx)
if (scriptEntry.responseEnd > 0 && scriptEntry.responseStart > 0) {
return true;
}
if (scriptEntry.responseStatus === 0) {
return true;
}
}
return false;
}
/**
* Checks if an existing script has a request error using Performance API.
*
* @param scriptUrl - The URL of the script to check.
* @returns True if the script has failed to load due to a network/HTTP error.
*/
function hasScriptRequestError(scriptUrl: string): boolean {
if (typeof window === 'undefined' || !('performance' in window)) {
return false;
}
const entries = performance.getEntriesByName(scriptUrl, 'resource') as PerformanceEntry[];
const scriptEntry = entries.find((e): e is PerformanceResourceTiming => {
return (e as PerformanceResourceTiming).entryType === 'resource';
});
if (!scriptEntry) {
return false;
}
// Clear-cut failure: no response observed. Sizes may be 0 cross-origin even on success (no TAO).
return scriptEntry.responseEnd === 0;
}
🤖 Prompt for AI Agents
In packages/shared/src/loadClerkJsScript.ts around lines 62 to 98, the
implementation uses properties not present on PerformanceResourceTiming
(responseStatus) and treats transferSize/decodedBodySize === 0 as an error which
causes false positives for cross-origin loads; change to use
performance.getEntriesByName(scriptUrl) (typed as PerformanceResourceTiming[])
to get the relevant entries, pick the most recent entry (if any), and only treat
the script as failed when no response was observed (entry.responseEnd === 0);
remove checks for transferSize/decodedBodySize and responseStatus to fix the TS
error and reduce false positives.

Comment on lines 187 to 191
if (!opts?.publishableKey) {
errorThrower.throwMissingPublishableKeyError();
return null;
}

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 | 🔴 Critical

Don’t require publishableKey when a direct clerkJSUrl is provided

This throws even when a script URL is explicitly supplied. Allow either pk or URL.

-  if (!opts?.publishableKey) {
+  if (!opts?.publishableKey && !opts?.clerkJSUrl) {
     errorThrower.throwMissingPublishableKeyError();
     return null;
   }
📝 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
if (!opts?.publishableKey) {
errorThrower.throwMissingPublishableKeyError();
return null;
}
if (!opts?.publishableKey && !opts?.clerkJSUrl) {
errorThrower.throwMissingPublishableKeyError();
return null;
}
🤖 Prompt for AI Agents
In packages/shared/src/loadClerkJsScript.ts around lines 187 to 191, the current
check unconditionally throws a missing publishableKey error even when a direct
clerkJSUrl is supplied; change the guard to only require opts.publishableKey
when opts.clerkJSUrl is not provided (e.g., if neither publishableKey nor
clerkJSUrl exist then throw), keeping the existing
errorThrower.throwMissingPublishableKeyError() path for the
publishableKey-missing case and returning null as before; ensure the condition
handles undefined/null values safely (opts may be undefined) so supplying a
clerkJSUrl bypasses the publishableKey requirement.

Copy link

pkg-pr-new bot commented Sep 26, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6b3efd1

* @param scriptUrl - The URL of the script to check.
* @returns True if the script has failed to load due to a network/HTTP error.
*/
function hasScriptRequestError(scriptUrl: string): boolean {
Copy link
Member

Choose a reason for hiding this comment

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

I like this!

existingScript.remove();
} else {
try {
return await waitForClerkWithTimeout(timeout);
Copy link
Member

Choose a reason for hiding this comment

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

I'm having seconds thoughts about this particular return here. I checked the code and it seems that there's no retry logic in IsomorphicClerk (the calling site) or in loadClerkJsScript - the retry logic is in loadScript which will not be called if we return here.

So, if I understand correctly, if the <script> fails to load and we're going to remove it and implicitly retry via loadScript. If, however, the script hasn't errored at the point of the check, we're going to wait for a timeout and then completely fail. This is good because the status will change, but it feels like we should at least trigger a few retries first before failing completely. Failing to load the script cannot be recovered from the perspective of the user/dev once status switches so retrying makes sense

Copy link
Member Author

Choose a reason for hiding this comment

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

@nikosdouvlis I believe this still works because of return await. The function will not return until the promise from waitForClerkWithTimeout is resolved, which means it should throw if we can't detect that Clerk loaded in time.

I did spend some time trying to refactor this part on Friday though, I think it could be clearer what's going on. I will revisit it again today!

Copy link
Member

@nikosdouvlis nikosdouvlis Sep 29, 2025

Choose a reason for hiding this comment

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

I haven't tested it locally yet, but what you're saying makes sense! The current implementation just bails and does not retry if the existing script fails to load, your fix is a nice improvement!

The await part is tricky though, if someone accidentally removes the keyword, retrying for this case will break and TS won't catch it as the return signature will not change (still a promise). Switching to then().catch might be a good first step towards making this a bit harder to break?

Another idea would be to move the retry logic from loadScript on level up (inside loadClerkJsScript) so its a little easier to understand who's responsible to handle the error thrown, but Im not 100% sold on that idea yet

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.

2 participants