-
Notifications
You must be signed in to change notification settings - Fork 393
feat(shared): Improve error handling for clerk-js loading #6856
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: be1530f The changes in this PR will be included in the next version bump. This PR includes changesets to release 19 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 a Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor App as Application
participant LCS as loadClerkJsScript
participant LS as loadScript
participant Net as Network/CDN
App->>LCS: loadClerkJsScript(...)
note right of LCS: optional setClerkJsLoadingErrorPackageName
LCS->>LS: loadScript(src, opts)
LS->>Net: request script
alt Success
Net-->>LS: script loaded
LS-->>LCS: resolve(script)
LCS-->>App: resolve(clerk)
else Script load error
Net-->>LS: error event (may include event.error)
LS-->>LCS: reject(event.error or Error("Failed to load script"))
LCS-->>App: reject(ClerkRuntimeError{ code, cause: event.error })
else Timeout
LCS-->>App: reject(ClerkRuntimeError{ code: TIMEOUT, cause: Error("timeout") })
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~40 minutes Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (1)
🧰 Additional context used📓 Path-based instructions (8)**/*.{js,jsx,ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/*.{ts,tsx,d.ts}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/*.{test,spec}.{js,jsx,ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Files:
**/*.{js,ts,tsx,jsx}📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Files:
**/__tests__/**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
Files:
⏰ 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)
🔇 Additional comments (2)
Comment |
@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: |
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 (3)
packages/shared/src/loadScript.ts (1)
22-28
: Avoid continuing after reject; add early returns.Currently the code rejects but continues to create/append a script, risking multiple settle attempts and unexpected DOM mutations.
Apply:
if (!src) { - reject(new Error(NO_SRC_ERROR)); + reject(new Error(NO_SRC_ERROR)); + return; } if (!document || !document.body) { - reject(new Error(NO_DOCUMENT_ERROR)); + reject(new Error(NO_DOCUMENT_ERROR)); + return; }packages/shared/src/loadClerkJsScript.ts (2)
71-119
: Fix TDZ bug when Clerk is already loaded before pollInterval is defined.Calling
checkAndResolve()
beforepollInterval
is initialized can cause a ReferenceError if Clerk is already loaded.Apply:
function waitForClerkWithTimeout(timeoutMs: number): Promise<HTMLScriptElement | null> { return new Promise((resolve, reject) => { let resolved = false; - const cleanup = (timeoutId: ReturnType<typeof setTimeout>, pollInterval: ReturnType<typeof setInterval>) => { - clearTimeout(timeoutId); - clearInterval(pollInterval); - }; + let pollInterval: ReturnType<typeof setInterval> | undefined; + const cleanup = (timeoutId: ReturnType<typeof setTimeout>) => { + clearTimeout(timeoutId); + if (pollInterval) { + clearInterval(pollInterval); + } + }; const checkAndResolve = () => { if (resolved) { return; } if (isClerkProperlyLoaded()) { resolved = true; - cleanup(timeoutId, pollInterval); + cleanup(timeoutId); resolve(null); } }; const handleTimeout = () => { if (resolved) { return; } resolved = true; - cleanup(timeoutId, pollInterval); + cleanup(timeoutId); if (!isClerkProperlyLoaded()) { reject(new ClerkRuntimeError(FAILED_TO_LOAD_ERROR, { code: ERROR_CODE_TIMEOUT })); } else { resolve(null); } }; const timeoutId = setTimeout(handleTimeout, timeoutMs); - - checkAndResolve(); - - const pollInterval = setInterval(() => { + pollInterval = setInterval(() => { if (resolved) { - clearInterval(pollInterval); + if (pollInterval) clearInterval(pollInterval); return; } checkAndResolve(); }, 100); + // Run one immediate check after pollInterval is initialized + checkAndResolve(); }); }
160-175
: Propagate underlying loadScript errors and avoid unhandled rejections.Current code fires
loadScript(...).catch(throw ...)
without awaiting or returning it, leading to an unhandled rejection and causing the caller to only see a timeout. Also,error.message
access will throw iferror
is undefined.Apply:
- const loadPromise = waitForClerkWithTimeout(timeout); - - loadScript(clerkJsScriptUrl(opts), { - async: true, - crossOrigin: 'anonymous', - nonce: opts.nonce, - beforeLoad: applyClerkJsScriptAttributes(opts), - }).catch(error => { - throw new ClerkRuntimeError(FAILED_TO_LOAD_ERROR + (error.message ? `, ${error.message}` : ''), { - code: ERROR_CODE, - cause: error, - }); - }); - - return loadPromise; + try { + await loadScript(clerkJsScriptUrl(opts), { + async: true, + crossOrigin: 'anonymous', + nonce: opts.nonce, + beforeLoad: applyClerkJsScriptAttributes(opts), + }); + } catch (error: unknown) { + const msg = + error && typeof error === 'object' && 'message' in error ? String((error as any).message) : ''; + throw new ClerkRuntimeError(FAILED_TO_LOAD_ERROR + (msg ? `, ${msg}` : ''), { + code: ERROR_CODE, + cause: error instanceof Error ? error : undefined, + }); + } + + return waitForClerkWithTimeout(timeout);
🧹 Nitpick comments (6)
packages/shared/src/loadScript.ts (2)
17-19
: Make opts optional to match usage and avoid forcing callers to pass{}
.You already guard with
opts || {}
.Apply:
-export async function loadScript(src = '', opts: LoadScriptOptions): Promise<HTMLScriptElement> { +export async function loadScript(src = '', opts?: LoadScriptOptions): Promise<HTMLScriptElement> {
48-51
: Only set nonce when provided.Avoid assigning
undefined
to a DOM string property.Apply:
- script.src = src; - script.nonce = nonce; + script.src = src; + if (nonce) { + script.nonce = nonce; + }packages/shared/src/loadClerkJsScript.ts (1)
162-167
: Avoid setting nonce twice.Nonce is set both via loadScript’s
nonce
option and again inbeforeLoad
through attributes. Pick one to prevent churn.Proposed: drop the
nonce: opts.nonce
here and keep it inapplyClerkJsScriptAttributes
, or vice‑versa.packages/shared/src/errors/runtimeError.ts (3)
21-25
: Broaden cause type to unknown for interoperability.Callers may pass non-Error causes (e.g., DOM Events). Using
unknown
avoids type mismatches while encouraging narrowing at use sites.Apply:
- /** - * The original error that was caught to throw an instance of ClerkRuntimeError. - */ - cause?: Error; + /** + * The original error that triggered this runtime error. + */ + cause?: unknown;
26-26
: Accept unknown cause in constructor for the same reason.Apply:
- constructor(message: string, { code, cause }: { code: string; cause?: Error }) { + constructor(message: string, { code, cause }: { code: string; cause?: unknown }) {
27-36
: Optionally pass cause to Error for native chaining (when supported).If your TS lib target includes ES2022.Error, consider chaining cause to preserve stacks.
Example:
// Replace super(_message) with: // super(_message, cause ? { cause } : undefined as any);Gate behind lib support to avoid type errors.
📜 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 (4)
.changeset/tangy-bees-follow.md
(1 hunks)packages/shared/src/errors/runtimeError.ts
(2 hunks)packages/shared/src/loadClerkJsScript.ts
(3 hunks)packages/shared/src/loadScript.ts
(3 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{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/errors/runtimeError.ts
packages/shared/src/loadClerkJsScript.ts
packages/shared/src/loadScript.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/errors/runtimeError.ts
packages/shared/src/loadClerkJsScript.ts
packages/shared/src/loadScript.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/shared/src/errors/runtimeError.ts
packages/shared/src/loadClerkJsScript.ts
packages/shared/src/loadScript.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/errors/runtimeError.ts
packages/shared/src/loadClerkJsScript.ts
packages/shared/src/loadScript.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/errors/runtimeError.ts
packages/shared/src/loadClerkJsScript.ts
packages/shared/src/loadScript.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/errors/runtimeError.ts
packages/shared/src/loadClerkJsScript.ts
packages/shared/src/loadScript.ts
.changeset/**
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Automated releases must use Changesets.
Files:
.changeset/tangy-bees-follow.md
🧬 Code graph analysis (1)
packages/shared/src/loadClerkJsScript.ts (1)
packages/shared/src/errors/runtimeError.ts (1)
ClerkRuntimeError
(9-50)
⏰ 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 (2)
.changeset/tangy-bees-follow.md (1)
1-6
: Changeset scope and bump look appropriate.Minor bump matches the addition of a new exported helper and enhanced error behavior.
packages/shared/src/loadClerkJsScript.ts (1)
3-3
: Import path is correct: ClerkRuntimeError is re-exported from ‘./error’ barrel.
packages/shared/src/loadScript.ts
Outdated
/** | ||
* | ||
*/ |
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.
🛠️ Refactor suggestion | 🟠 Major
Replace placeholder JSDoc with real API docs.
Document params, return type, and error cases. This is a public utility.
Apply:
-/**
- *
- *
- */
+/**
+ * Dynamically injects a <script> tag and resolves when it loads.
+ *
+ * Errors:
+ * - Rejects with Error(NO_SRC_ERROR) when src is empty.
+ * - Rejects with Error(NO_DOCUMENT_ERROR) when document/body is unavailable (SSR).
+ * - Rejects with a descriptive Error on script load failure.
+ *
+ * @param src - Script URL to load.
+ * @param opts - Script attributes and lifecycle hooks.
+ * @returns A promise resolving with the created script element after it loads.
+ */
📝 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.
/** | |
* | |
*/ | |
/** | |
* Dynamically injects a <script> tag and resolves when it loads. | |
* | |
* Errors: | |
* - Rejects with Error(NO_SRC_ERROR) when src is empty. | |
* - Rejects with Error(NO_DOCUMENT_ERROR) when document/body is unavailable (SSR). | |
* - Rejects with a descriptive Error on script load failure. | |
* | |
* @param src - Script URL to load. | |
* @param opts - Script attributes and lifecycle hooks. | |
* @returns A promise resolving with the created script element after it loads. | |
*/ |
🤖 Prompt for AI Agents
In packages/shared/src/loadScript.ts around lines 14 to 16, the current
placeholder JSDoc must be replaced with a complete API docblock: add
descriptions for each parameter (name, type, purpose, optional/defaults), the
exact return type and shape (including Promise if async), and list possible
error cases/conditions that callers should handle (including thrown errors and
rejection reasons). Keep wording concise, use standard JSDoc tags (@param,
@returns, @throws/@rejects), mention side effects (DOM/script insertion) and
intended audience (public utility), and ensure examples or usage notes are
included if helpful.
packages/shared/src/loadScript.ts
Outdated
/** | ||
* | ||
*/ |
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.
Not sure how this ended up here 🙃
const ERROR_CODE = 'failed_to_load_clerk_js'; | ||
const ERROR_CODE_TIMEOUT = 'failed_to_load_clerk_js_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.
Is this helping because we want to better track why an error is thrown ?
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.
Correct 👍
Description
This improves error handling during clerk-js loading. Specifically, it uses our
ClerkRuntimeError
class and ensures we are propagating underlying errors up so we can see the cause. Previously, we swallowed errors and only threw a generic error with a generic message ("Clerk: Failed to load Clerk").Additionally, I've added an optional
cause
option toClerkRuntimeError
that allows us to pass along the original, unwrapped error for additional introspect (h/t @jacekradko)Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Bug Fixes
Chores