Skip to content

Conversation

@brkalow
Copy link
Member

@brkalow brkalow commented Sep 26, 2025

Description

Adds retries for clerk-js script loading in more scenarios, specifically attempts to recover from the case where the clerk-js script tag is injected on the server and fails to load before an error handler can be attached. In this case, we don't have any way of knowing if the script is loading or has errored. This PR introduces logic to attempt to detect when the script has failed to load before listeners are attached.

Additional integration test cases were also added that verify this behavior.

Checklist

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

Type of change

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

Summary by CodeRabbit

  • New Features

    • Adds a client-side status page showing Clerk loading, loaded, degraded, and failed states.
  • Bug Fixes

    • Detects and removes failed or stalled script loads, retries loading, and cleans up stale scripts.
    • Fixes a UI text typo in the loading/degraded messaging.
  • Refactor

    • Unifies script load/retry/cleanup behavior for more reliable startup.
  • Documentation

    • Updates comments and JSDoc to clarify error-detection and retry semantics.
  • Tests

    • Adds extensive resiliency tests for script/network failures and recovery.

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

@changeset-bot
Copy link

changeset-bot bot commented Sep 26, 2025

🦋 Changeset detected

Latest commit: ed9dd9f

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

This PR includes changesets to release 22 packages
Name Type
@clerk/shared Minor
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/chrome-extension Patch
@clerk/clerk-js Patch
@clerk/elements Patch
@clerk/expo-passkeys Patch
@clerk/clerk-expo Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/nextjs Patch
@clerk/nuxt Patch
@clerk/react-router Patch
@clerk/clerk-react Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/testing Patch
@clerk/themes Patch
@clerk/types Patch
@clerk/vue Patch
@clerk/localizations Patch

Not sure what this means? Click here to learn what changesets are.

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

@vercel
Copy link

vercel bot commented 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 Nov 25, 2025 4:18am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

Walkthrough

Adds script-load error detection and retry/cleanup logic to the Clerk JS loader; adds a client-side Next.js ClerkStatusPage that renders Clerk loading/status states; restructures and extends resiliency tests to simulate transient failures, script load errors, and recovery flows.

Changes

Cohort / File(s) Summary of changes
Clerk JS loader resilience
packages/shared/src/loadClerkJsScript.ts
Adds hasScriptRequestError(scriptUrl) using the Performance API; updates loadClerkJsScript to inspect existing scripts, remove errored or timed-out scripts, wait-with-timeout for Clerk readiness, and retry loading a fresh script; unifies URL handling and updates JSDoc/comments.
Next.js Clerk status page
integration/templates/next-app-router/src/app/clerk-status/page.tsx
New client component ClerkStatusPage (default export) that uses useClerk and renders status messages and conditional wrappers: ClerkLoaded, ClerkLoading, ClerkFailed, ClerkDegraded.
Resiliency tests
integration/tests/resiliency.test.ts
Reorganized under describe('loading resiliency', ...); adds extensive tests covering script load failures, transient HTTP 5xx/4xx scenarios, slow networks, retry/recovery behavior, token-refresh checks, and expanded state/UI assertions.
Minor UI text fix
integration/templates/react-vite/src/clerk-status/index.tsx
Fixes a typo in the ClerkLoading component text ("regraded" → "degraded").
Release notes
.changeset/lazy-items-crash.md
Adds changeset entry describing improved error handling and retry logic when loading @clerk/clerk-js (release note content).

Sequence Diagram(s)

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

  App->>Loader: loadClerkJsScript(options)
  Loader->>DOM: locate existing <script src=scriptUrl>
  alt existing script found
    Loader->>Perf: hasScriptRequestError(scriptUrl)?
    alt error detected
      Loader->>DOM: remove existing <script>
      note right of Loader `#DDDDFF`: cleanup before retry
      Loader->>Net: load new script (loadScript with 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 (with timeout)
      alt ready before timeout
        Loader-->>App: resolve
      else timeout
        Loader->>DOM: remove existing <script>
        note right of Loader `#DDDDFF`: retry with 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

🎯 4 (Complex) | ⏱️ ~45 minutes

Potential review focal points:

  • packages/shared/src/loadClerkJsScript.ts: correctness of Performance API usage, detection heuristics, race conditions when removing/injecting script elements, and timeout/retry semantics.
  • integration/tests/resiliency.test.ts: test stability (timing/flakiness), accuracy of simulated network responses and waits, and clarity of assertions.
  • integration/templates/next-app-router/src/app/clerk-status/page.tsx: client-only usage and proper useClerk handling.

Poem

I tidy tags beneath moonbeams' glow,
If scripts trip up, I nudge them so.
I pluck the broken, fetch a new,
Then watch the Clerk awaken true.
A rabbit hops — resilient and spry — to keep the loaders flying high. 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ 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 directly describes the main feature: intelligent retry logic for existing clerk-js scripts, which aligns with the core change in loadClerkJsScript.ts and the new resiliency tests.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • 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.

@pkg-pr-new
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: ed9dd9f

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

@clerk-cookie
Copy link
Collaborator

Hello 👋

We currently close PRs after 60 days of inactivity. It's been 50 days since the last update here. If we missed this PR, please reply here. Otherwise, we'll close this PR in 10 days.

Thanks for being a part of the Clerk community! 🙏

@clerk-cookie clerk-cookie added Stale and removed Stale labels Nov 19, 2025
Copy link
Member Author

Choose a reason for hiding this comment

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

Recommend viewing without whitespace changes: https://github.com/clerk/javascript/pull/6860/files?w=1

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 (1)
integration/tests/resiliency.test.ts (1)

49-53: Consider replacing waitForTimeout with a more deterministic wait.

Using waitForTimeout can make tests flaky. Consider if this delay could be replaced with waiting for a specific condition, or add a comment explaining why this fixed delay is necessary before reload.

If the timeout is intentional (e.g., to ensure state is stable before reload), consider adding a clarifying comment:

       // Simulate developer coming back and client fails to load.
       await page.route('**/v1/client?**', route => route.fulfill(make500ClerkResponse()));

-      await page.waitForTimeout(1_000);
+      // Allow time for route interception to be fully registered before reload
+      await page.waitForTimeout(1_000);
       await page.reload();
📜 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 6b3efd1 and 56a3aef.

📒 Files selected for processing (2)
  • integration/templates/next-app-router/src/app/clerk-status/page.tsx (1 hunks)
  • integration/tests/resiliency.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.{ts,tsx,js,jsx}

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

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

Prefer importing types from @clerk/shared/types instead of the deprecated @clerk/types alias

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.tsx

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

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

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

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
**/*.{md,tsx}

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

Update documentation for API changes

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
**/*.{jsx,tsx}

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

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

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

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

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

Files:

  • integration/tests/resiliency.test.ts
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}

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

Use real Clerk instances for integration tests

Files:

  • integration/tests/resiliency.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
integration/templates/next-app-router/src/app/clerk-status/page.tsx (1)

1-6: LGTM - Component structure is appropriate for testing purposes.

The component correctly uses the 'use client' directive, properly destructures loaded and status from useClerk(), and provides comprehensive visibility into all Clerk states for integration testing.

integration/tests/resiliency.test.ts (3)

37-82: Comprehensive token refresh resilience test.

This test effectively validates that signed-in users can recover session tokens when the client endpoint fails. The approach of comparing tokens before and after the outage is sound.


257-396: Excellent coverage of script loading failure scenarios.

The test suite comprehensively covers transient network failures, HTTP 500/503 responses, retry exhaustion, and slow network conditions. The use of request counting to verify retry behavior and appropriate timeouts for exponential backoff scenarios is well implemented.


144-254: Well-structured Clerk.status state transition tests.

The tests thoroughly validate status transitions for normal flow, script loading failures, and client/environment failures leading to degraded state. The assertions properly verify both hook-based status values and component visibility states.

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 (1)
integration/tests/resiliency.test.ts (1)

37-82: Consider removing or replacing the arbitrary timeout.

Line 52 uses page.waitForTimeout(1_000) before reload, which can introduce test flakiness. If the delay is intended to ensure some state is set up, consider using a more deterministic wait (e.g., waiting for a specific element or network response).

-      await page.waitForTimeout(1_000);
       await page.reload();

If there's a specific reason for this delay (e.g., ensuring cookies are persisted), a comment would help clarify the intent.

📜 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 56a3aef and a33cc02.

📒 Files selected for processing (3)
  • integration/templates/next-app-router/src/app/clerk-status/page.tsx (1 hunks)
  • integration/templates/react-vite/src/clerk-status/index.tsx (1 hunks)
  • integration/tests/resiliency.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • integration/templates/react-vite/src/clerk-status/index.tsx
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.{ts,tsx,js,jsx}

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

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

Prefer importing types from @clerk/shared/types instead of the deprecated @clerk/types alias

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.tsx

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

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

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

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
**/*.{md,tsx}

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

Update documentation for API changes

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
**/*.{jsx,tsx}

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

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

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
**/*.{ts,tsx}

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

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • integration/templates/next-app-router/src/app/clerk-status/page.tsx
  • integration/tests/resiliency.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

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

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

Files:

  • integration/tests/resiliency.test.ts
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}

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

Use real Clerk instances for integration tests

Files:

  • integration/tests/resiliency.test.ts
🧬 Code graph analysis (1)
integration/templates/next-app-router/src/app/clerk-status/page.tsx (1)
integration/templates/react-vite/src/clerk-status/index.tsx (1)
  • ClerkStatusPage (3-34)
⏰ 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). (30)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15, RQ)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
integration/templates/next-app-router/src/app/clerk-status/page.tsx (1)

1-35: LGTM! Clean implementation for testing Clerk status states.

This component effectively covers all Clerk status scenarios (loading, ready, degraded, error) using both direct status checks and wrapper components, which is appropriate for integration testing purposes.

One minor observation: Line 23 has "(comp) Clerk is loaded,(ready or degraded)" with no space after the comma, matching the react-vite version. This is fine for consistency.

integration/tests/resiliency.test.ts (3)

144-254: Comprehensive status transition tests.

The Clerk.status test block thoroughly covers all status states (loading, ready, degraded, error) and verifies proper transitions. The timeout comments explaining the 15-second script loading timeout are helpful for maintainability.


257-396: Well-structured script loading resilience tests.

The test suite effectively covers various failure scenarios:

  • Transient network failures with single retry
  • HTTP 500/503 errors with retry recovery
  • Exhausted retries leading to error state
  • Slow network conditions

The use of requestCount to verify retry behavior is a solid pattern for ensuring the retry logic is actually exercised.


84-142: LGTM!

The devBrowser resiliency test correctly simulates the scenario where dev browser JWT doesn't match the instance, verifies proper 401 handling, and ensures route cleanup with page.unrouteAll() before verifying the dev_browser response.

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 (1)
.changeset/lazy-items-crash.md (1)

5-5: Consider adding more specific details to the changelog entry.

The description is quite generic. Consider mentioning what specifically improved—for example, the new error detection mechanism, the retry behavior for existing scripts, or the timeout handling. This helps users understand the concrete benefits.

For reference, a more detailed entry might look like:

Improve error handling and retry logic when loading `@clerk/clerk-js` by detecting script load failures and cleaning up failed scripts before retrying, with timeout safeguards.
📜 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 a33cc02 and ed9dd9f.

📒 Files selected for processing (1)
  • .changeset/lazy-items-crash.md (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

Copy link
Member

@wobsoriano wobsoriano left a comment

Choose a reason for hiding this comment

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

love it! thanks

@brkalow brkalow merged commit 8376789 into main Dec 4, 2025
46 checks passed
@brkalow brkalow deleted the brk.feat/clerk-js-retry branch December 4, 2025 04:59
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.

5 participants