-
Notifications
You must be signed in to change notification settings - Fork 411
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
Conversation
🦋 Changeset detectedLatest commit: ed9dd9f The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 packages
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 |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughAdds 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Potential review focal points:
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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 assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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 || scriptUrlin thehasScriptRequestError(existingSrc)check.Verify that
data-clerk-js-scriptisn’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
|
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! 🙏 |
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.
Recommend viewing without whitespace changes: https://github.com/clerk/javascript/pull/6860/files?w=1
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
🧹 Nitpick comments (1)
integration/tests/resiliency.test.ts (1)
49-53: Consider replacingwaitForTimeoutwith a more deterministic wait.Using
waitForTimeoutcan 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.
📒 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.tsxintegration/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.tsxintegration/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/typesinstead of the deprecated@clerk/typesalias
Files:
integration/templates/next-app-router/src/app/clerk-status/page.tsxintegration/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.tsxintegration/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Implement type guards forunknowntypes using the patternfunction isType(value: unknown): value is Type
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details in classes
Useprotectedfor inheritance hierarchies
Usepublicexplicitly 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 likeOmit,Partial, andPickfor 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
Useconst assertionswithas constfor literal types
Usesatisfiesoperator 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.tsxintegration/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
loadedandstatusfromuseClerk(), 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.
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: 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.
📒 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.tsxintegration/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.tsxintegration/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/typesinstead of the deprecated@clerk/typesalias
Files:
integration/templates/next-app-router/src/app/clerk-status/page.tsxintegration/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.tsxintegration/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Implement type guards forunknowntypes using the patternfunction isType(value: unknown): value is Type
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details in classes
Useprotectedfor inheritance hierarchies
Usepublicexplicitly 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 likeOmit,Partial, andPickfor 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
Useconst assertionswithas constfor literal types
Usesatisfiesoperator 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.tsxintegration/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
requestCountto 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.
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: 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.
📒 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
wobsoriano
left a comment
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.
love it! thanks
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 testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Documentation
Tests
✏️ Tip: You can customize this high-level summary in your review settings.