Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
refactor(shared): Update exported error typeguard functions from error.ts, align error class naming by kduprey · Pull Request #7490 · clerk/javascript · GitHub
Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared): Update exported error typeguard functions from error.ts, align error class naming by kduprey · Pull Request #7490 · clerk/javascript · GitHub
Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared): Update exported error typeguard functions from error.ts, align error class naming by kduprey · Pull Request #7490 · clerk/javascript · GitHub
Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' refactor(shared): Update exported error typeguard functions from error.ts, align error class naming by kduprey · Pull Request #7490 · clerk/javascript · GitHub
Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared): Update exported error typeguard functions from error.ts, align error class naming by kduprey · Pull Request #7490 · clerk/javascript · GitHub
Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' refactor(shared): Update exported error typeguard functions from error.ts, align error class naming by kduprey · Pull Request #7490 · clerk/javascript · GitHub
Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); refactor(shared): Update exported error typeguard functions from error.ts, align error class naming by kduprey · Pull Request #7490 · clerk/javascript · GitHub
Skip to content

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming - #7490

Merged
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type
Dec 18, 2025
Merged

refactor(shared): Update exported error typeguard functions from error.ts, align error class naming#7490
kduprey merged 5 commits into
release/core-2from
kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type

Conversation

@kduprey

@kdupreykduprey commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Description

Currently, in handleError() in clerk-js/src/ui/utils/errorHandler.ts the function runs through each type of predefined error type we have and handles the error from there. If the error is a ClerkRuntimeError, the intended handler is never reached due to type overlap between ClerkAPIResponseError and ClerkRuntimeError.

Both interfaces extend ClerkError which causes ClerkRuntimeError error types to be handled by handleClerkApiError versus handleClerkRuntimeError given the order of the logic gates.

We have recently added createErrorTypeGuard() to properly check the error type against the provided interface, and utility functions were added to each error definition file (e.g. clerkRuntimeError.ts). We do have pre-existing functions in shared/src/errors/helpers.ts however, they are not using the new type guard check functions provided from each error definition file.

This removes the old/faulty error type checks from helpers.ts in favour of the new type guard functions, updates the exported functions in shared/src/error.ts, and also aligns the naming pattern for isClerkApiResponseError and isClerkAPIResponseError.

USER-4239

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

  • Refactor
    • Improved consistency in error handling functions and type guards
    • Enhanced error metadata support for API errors

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

…r.ts, align error class naming
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kdupreykduprey self-assigned this Dec 17, 2025
@changeset-bot

changeset-botBot commented Dec 17, 2025

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6741930

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

This PR includes changesets to release 22 packages
NameType
@clerk/sharedPatch
@clerk/agent-toolkitPatch
@clerk/astroPatch
@clerk/backendPatch
@clerk/chrome-extensionPatch
@clerk/clerk-jsPatch
@clerk/elementsPatch
@clerk/expo-passkeysPatch
@clerk/clerk-expoPatch
@clerk/expressPatch
@clerk/fastifyPatch
@clerk/nextjsPatch
@clerk/nuxtPatch
@clerk/react-routerPatch
@clerk/clerk-reactPatch
@clerk/remixPatch
@clerk/tanstack-react-startPatch
@clerk/testingPatch
@clerk/themesPatch
@clerk/typesPatch
@clerk/vuePatch
@clerk/localizationsPatch

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

vercelBot commented Dec 17, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

ProjectDeploymentReviewUpdated (UTC)
clerk-js-sandboxReadyReadyPreview, CommentDec 18, 2025 0:29am

@coderabbitai

coderabbitaiBot commented Dec 17, 2025

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This pull request refactors Clerk's error handling infrastructure by consolidating duplicate type guard implementations and aligning naming conventions. Type guards previously defined in helpers.ts are removed and replaced with imports from their respective error modules. Additionally, inconsistent "ClerkApi" naming patterns are standardized to "ClerkAPI" across type guards and class definitions.

Changes

Cohort / File(s)Summary
Changeset metadata
.changeset/sweet-singers-beg.md
Adds changeset entry documenting patch version bump for @clerk/shared with description of internal error handling refactor.
Type guard consolidation and import updates
packages/shared/src/errors/helpers.ts, packages/shared/src/errors/globalHookError.ts
Removes duplicate implementations of isClerkAPIResponseError and isClerkRuntimeError from helpers.ts; updates globalHookError.ts to import isClerkAPIResponseError from its source module instead of helpers.
Naming alignment for error classes and guards
packages/shared/src/errors/clerkApiError.ts, packages/shared/src/errors/clerkApiResponseError.ts
Renames ClerkApiErrorMeta to ClerkAPIErrorMeta and isClerkApiError to isClerkAPIError in clerkApiError.ts; renames isClerkApiResponseError to isClerkAPIResponseError in clerkApiResponseError.ts. ClerkAPIError class now includes readonly meta property and constructor for JSON parsing.
Public API re-export updates
packages/shared/src/error.ts
Adds re-exports of type guards isClerkAPIError, isClerkAPIResponseError, isClerkError, and isClerkRuntimeError directly from their respective modules; removes re-exports of isClerkAPIResponseError and isClerkRuntimeError from helpers aggregated export.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Areas requiring attention:
    • packages/shared/src/error.ts: Verify that public API re-export structure is correct and doesn't create naming conflicts or unintended duplicate exports.
    • packages/shared/src/errors/clerkApiError.ts: Validate the new constructor logic for JSON metadata parsing and ensure the meta property correctly reflects the type parameter.
    • Cross-file consistency: Confirm that all imports of renamed type guards throughout the codebase (especially isClerkAPIError and isClerkAPIResponseError) are properly updated.

Poem

🐰 Errors once tangled in helper's nest,
Now each guard stands its own test.
API names polished with care,
Type safety shines everywhere!
No more confusion, the path is clear—
Robust error handling draws near.

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check nameStatusExplanation
Description Check✅ PassedCheck skipped - CodeRabbit’s high-level summary is enabled.
Title check✅ PassedThe pull request title accurately describes the main refactoring changes: updating exported error typeguard functions and aligning error class naming conventions in the shared package.
Linked Issues check✅ PassedAll coding requirements from USER-4239 are met: old faulty error checks removed from helpers.ts, new per-error type guard functions integrated, exported functions updated in error.ts, and naming conventions aligned for isClerkAPIResponseError consistency.
Out of Scope Changes check✅ PassedAll changes are directly scoped to USER-4239 objectives: updating error type guards, aligning naming conventions, and fixing type overlap issues. No extraneous modifications detected.
Docstring Coverage✅ PassedDocstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

@kdupreykduprey changed the title refactor(errors): Update exported error typeguard functions from error.ts, align error class namingrefactor(shared): Update exported error typeguard functions from error.ts, align error class namingDec 17, 2025
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@pkg-pr-new

pkg-pr-newBot commented Dec 17, 2025

Copy link
Copy Markdown

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 6741930

@kduprey

Copy link
Copy Markdown
ContributorAuthor

@coderabbitai review

@coderabbitai

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitaicoderabbitaiBot left a comment

Copy link
Copy Markdown
Contributor

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)
packages/shared/src/errors/clerkApiError.ts (1)

9-35: Review type safety in generic parameter and constructor.

Several type safety considerations:

  1. Line 9: The generic parameter default is any, which bypasses TypeScript's type checking. Per coding guidelines, prefer unknown when the type is uncertain.

  2. Line 29: The metadata parsing uses as unknown as Meta, which completely bypasses type safety. The parsed metadata structure may not actually match the expected Meta type.

Consider this safer approach:

-export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = any> implements ClerkAPIErrorInterface {+export class ClerkAPIError<Meta extends ClerkAPIErrorMeta = ClerkAPIErrorMeta> implements ClerkAPIErrorInterface {
static kind = 'ClerkAPIError';
readonly code: string;
readonly message: string;
readonly longMessage: string | undefined;
readonly meta: Meta;
constructor(json: ClerkAPIErrorJSON) {
const parsedError = {
code: json.code,
message: json.message,
longMessage: json.long_message,
meta: {
paramName: json.meta?.param_name,
sessionId: json.meta?.session_id,
emailAddresses: json.meta?.email_addresses,
identifiers: json.meta?.identifiers,
zxcvbn: json.meta?.zxcvbn,
plan: json.meta?.plan,
isPlanUpgradePossible: json.meta?.is_plan_upgrade_possible,
- } as unknown as Meta,+ } as Meta,
};
this.code = parsedError.code;
this.message = parsedError.message;
this.longMessage = parsedError.longMessage;
this.meta = parsedError.meta;
}
}

This approach:

  • Uses ClerkAPIErrorMeta as the default instead of any
  • Removes the double assertion (as unknown as Meta)
  • Still allows flexibility for specific metadata types through the generic parameter
📜 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 54cd476 and d948e0d.

📒 Files selected for processing (6)
  • .changeset/sweet-singers-beg.md (1 hunks)
  • packages/shared/src/error.ts (1 hunks)
  • packages/shared/src/errors/clerkApiError.ts (2 hunks)
  • packages/shared/src/errors/clerkApiResponseError.ts (1 hunks)
  • packages/shared/src/errors/globalHookError.ts (2 hunks)
  • packages/shared/src/errors/helpers.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{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:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/errors/clerkApiResponseError.ts
  • packages/shared/src/errors/helpers.ts
  • packages/shared/src/errors/clerkApiError.ts
  • packages/shared/src/error.ts
  • packages/shared/src/errors/globalHookError.ts
🪛 LanguageTool
.changeset/sweet-singers-beg.md

[grammar] ~5-~5: Use a hyphen to join words.
Context: ...patch --- Refactor internal Clerk error handling functions

(QB_NEW_EN_HYPHEN)

⏰ 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). (10)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
🔇 Additional comments (6)
packages/shared/src/errors/helpers.ts (1)

1-4: LGTM! Type guard imports centralized.

The refactoring successfully replaces the previously faulty in-file type guard implementations with imports from their dedicated modules, aligning with the PR's core objective to fix type assertion issues.

packages/shared/src/errors/clerkApiError.ts (2)

4-4: LGTM! Type naming aligned.

The renaming from ClerkApiErrorMeta to ClerkAPIErrorMeta maintains consistency with the ClerkAPI* naming convention.


38-41: LGTM! Type guard renamed consistently.

The type guard renaming from isClerkApiError to isClerkAPIError aligns with the ClerkAPI* naming convention.

packages/shared/src/errors/globalHookError.ts (1)

1-1: LGTM! Import and usage updated consistently.

The import and predicates object key have been updated to use isClerkAPIResponseError, maintaining consistency with the renamed export. This is a breaking API change for ClerkGlobalHookError, but the migration has already been completed throughout the codebase—all consumers are using the new name isClerkAPIResponseError.

packages/shared/src/error.ts (1)

3-5: LGTM! Type guard exports refactored correctly.

The refactoring successfully consolidates type guard exports from their dedicated modules, addressing the core PR objective. Each error type now exports its own type guard:

  • isClerkAPIError from clerkApiError
  • isClerkAPIResponseError from clerkApiResponseError
  • isClerkError from clerkError
  • isClerkRuntimeError from clerkRuntimeError

This modular approach replaces the previous faulty type checks in helpers.ts.

Verify that the new export structure doesn't break existing consumers:

#!/bin/bash# Description: Verify imports of error type guards across the codebase# Check for imports from @clerk/shared/errors or @clerk/shared/error
rg -nP "import\s+.*\{\s*.*is(?:Clerk(?:API|Runtime)|Clerk).*\}" --type ts --type tsx -g '!packages/shared/**'

Also applies to: 13-13

packages/shared/src/errors/clerkApiResponseError.ts (1)

49-60: Naming convention properly aligned - migration complete.

The type guard renaming from isClerkApiResponseError to isClerkAPIResponseError correctly aligns with the established ClerkAPI* naming convention. The implementation is correct, JSDoc is properly documented, and all usages across the codebase have been successfully updated to the new convention. The only historical reference to the old name appears in the changelog documenting the original functionality.

… todo for core 3 breaking change
Signed-off-by: Kenton Duprey <kenton@clerk.dev>

@tmilewskitmilewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Seems 👍

@kduprey
kduprey merged commit 2cd4da9 into release/core-2Dec 18, 2025
138 of 143 checks passed
@kduprey
kduprey deleted the kenton/user-4239-fix-clerksharederrors-pkg-type-assertions-due-to-type branch December 18, 2025 10:53
kduprey pushed a commit that referenced this pull request Dec 18, 2025
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

@kduprey@tmilewski@octoper