-
Notifications
You must be signed in to change notification settings - Fork 391
feat(shared): Intelligent retries for existing clerk-js script #6860
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughImplements 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests
Comment |
* @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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I like this!
There was a problem hiding this 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 catchThrowing 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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 guardReplace 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 thehasScriptRequestError(existingSrc)
check.Verify that
data-clerk-js-script
isn’t referenced anywhere in code, docs, or examples before removing it.
/** | ||
* 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; | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
/** | |
* 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.
if (!opts?.publishableKey) { | ||
errorThrower.throwMissingPublishableKeyError(); | ||
return null; | ||
} | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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.
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
* @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 { |
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
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
Description
Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit