Skip to content

Conversation

@kduprey
Copy link
Member

@kduprey kduprey commented Dec 18, 2025

Description

This PR ports over #7490 into core 3, and also adds a minor breaking change to ClerkAPIError.kind value to match the class name with a codemod.

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

  • Breaking Changes

    • Error kind string renamed to match new naming — update any direct string checks you rely on.
  • New Features

    • Error classes now export their corresponding type-guard alongside them for simpler imports.
    • Type guards use a cross-bundle detection path to better recognize errors across packages.
  • Bug Fixes

    • UI error-handling updated to use the renamed type-guard to ensure correct error mapping.
  • Documentation

    • Added upgrade note explaining the error kind rename and migration guidance.

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

…demod for breaking change

Signed-off-by: Kenton Duprey <kenton@clerk.dev>
Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kduprey kduprey requested a review from tmilewski December 18, 2025 17:49
@kduprey kduprey self-assigned this Dec 18, 2025
@changeset-bot
Copy link

changeset-bot bot commented Dec 18, 2025

🦋 Changeset detected

Latest commit: 233d6a1

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

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

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

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

@vercel
Copy link

vercel bot commented Dec 18, 2025

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

Project Deployment Review Updated (UTC)
clerk-js-sandbox Ready Ready Preview, Comment Dec 19, 2025 5:26pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 18, 2025

📝 Walkthrough

Walkthrough

Refactors internal error handling in @clerk/shared: exports each error class paired with its type-guard, moves previously local guards out of helpers, renames ApiAPI in types and guards, adds a readonly meta property and a constructor to ClerkAPIError, and updates its static kind to "ClerkAPIError". createErrorTypeGuard gains a duck-typing path that checks constructor.kind. Two helper functions were removed and imported from their modules. Changeset files include a patch entry and a separate entry setting @clerk/shared to major and @clerk/upgrade to minor.

Pre-merge checks

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately describes the main change: updating exported error type guard functions in error.ts and porting changes from core 2 to core 3.

📜 Recent review details

Configuration used: Repository YAML (base), Organization UI (inherited)

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 2ac8198 and b4ad421.

📒 Files selected for processing (2)
  • packages/ui/src/components/Checkout/CheckoutPage.tsx (1 hunks)
  • packages/ui/src/components/Checkout/parts.tsx (1 hunks)
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
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/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.tsx

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

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

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

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.{md,tsx}

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

Update documentation for API changes

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.{jsx,tsx}

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

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

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.{ts,tsx}

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

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

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*.{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/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

**/*: Only comment on issues that would block merging, ignore minor or stylistic concerns.
Restrict feedback to errors, security risks, or functionality-breaking problems.
Do not post comments on code style, formatting, or non-critical improvements.
Keep reviews short: flag only issues that make the PR unsafe to merge.
Group similar issues into a single comment instead of posting multiple notes.
Skip repetition: if a pattern repeats, mention it once at a summary level only.
Do not add general suggestions, focus strictly on merge-blocking concerns.
If there are no critical problems, respond with minimal approval (e.g., 'Looks good'). Do not add additional review.
Avoid line-by-line commentary unless it highlights a critical bug or security hole.
Highlight only issues that could cause runtime errors, data loss, or severe maintainability issues.
Ignore minor optimization opportunities, focus solely on correctness and safety.
Provide a top-level summary of critical blockers rather than detailed per-line notes.
Comment only when the issue must be resolved before merge, otherwise remain silent.
When in doubt, err on the side of fewer comments, brevity and blocking issues only.
Avoid posting any refactoring issues.

Files:

  • packages/ui/src/components/Checkout/CheckoutPage.tsx
  • packages/ui/src/components/Checkout/parts.tsx
⏰ 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). (25)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 18, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@7509

@clerk/upgrade

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

@clerk/vue

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

commit: 233d6a1

@kduprey
Copy link
Member Author

kduprey commented Dec 18, 2025

!allow-major

… 'kind' property

Signed-off-by: Kenton Duprey <kenton@clerk.dev>
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Repository YAML (base), Organization UI (inherited)

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 696ea44 and 2ac8198.

📒 Files selected for processing (1)
  • packages/shared/src/errors/createErrorTypeGuard.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/errors/createErrorTypeGuard.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/createErrorTypeGuard.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/errors/createErrorTypeGuard.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/createErrorTypeGuard.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/createErrorTypeGuard.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/errors/createErrorTypeGuard.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/createErrorTypeGuard.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/createErrorTypeGuard.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/createErrorTypeGuard.ts
**/*

⚙️ CodeRabbit configuration file

If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.

**/*: Only comment on issues that would block merging, ignore minor or stylistic concerns.
Restrict feedback to errors, security risks, or functionality-breaking problems.
Do not post comments on code style, formatting, or non-critical improvements.
Keep reviews short: flag only issues that make the PR unsafe to merge.
Group similar issues into a single comment instead of posting multiple notes.
Skip repetition: if a pattern repeats, mention it once at a summary level only.
Do not add general suggestions, focus strictly on merge-blocking concerns.
If there are no critical problems, respond with minimal approval (e.g., 'Looks good'). Do not add additional review.
Avoid line-by-line commentary unless it highlights a critical bug or security hole.
Highlight only issues that could cause runtime errors, data loss, or severe maintainability issues.
Ignore minor optimization opportunities, focus solely on correctness and safety.
Provide a top-level summary of critical blockers rather than detailed per-line notes.
Comment only when the issue must be resolved before merge, otherwise remain silent.
When in doubt, err on the side of fewer comments, brevity and blocking issues only.
Avoid posting any refactoring issues.

Files:

  • packages/shared/src/errors/createErrorTypeGuard.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (25)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)

Comment on lines +30 to +37
// Use duck-typing with 'kind' property to handle cross-bundle scenarios
// where instanceof fails due to different class instances
if (ErrorClass.kind && typeof target === 'object' && target !== null && 'constructor' in target) {
const targetConstructor = (target as { constructor?: { kind?: string } }).constructor;
if (targetConstructor?.kind === ErrorClass.kind) {
return true;
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Critical: Duck-typing check allows non-Error objects to pass type guard.

The duck-typing check only validates constructor.kind without verifying the target is an actual Error instance. This allows any plain object with a matching constructor.kind property to pass:

const fakeError = { constructor: { kind: 'ClerkAPIError' } };
isClerkAPIError(fakeError); // returns true, but it's not an Error

This violates the type guard's promise that error is InstanceType<T> and can cause runtime errors when code expects actual Error properties/methods.

🔎 Proposed fix to validate Error instance first
 // Use duck-typing with 'kind' property to handle cross-bundle scenarios
 // where instanceof fails due to different class instances
-if (ErrorClass.kind && typeof target === 'object' && target !== null && 'constructor' in target) {
+if (ErrorClass.kind && target instanceof Error && 'constructor' in target) {
   const targetConstructor = (target as { constructor?: { kind?: string } }).constructor;
   if (targetConstructor?.kind === ErrorClass.kind) {
     return true;
   }
 }
🤖 Prompt for AI Agents
In packages/shared/src/errors/createErrorTypeGuard.ts around lines 30 to 37, the
duck-typing branch currently returns true based only on constructor.kind which
lets arbitrary objects pass as errors; update the guard to first verify the
target has the shape of a real Error (e.g., is an object, not null, has a string
'message' property and optionally a string 'name' or 'stack') before checking
target.constructor?.kind === ErrorClass.kind, and only then return true; keep
the existing cross-bundle kind check but gate it behind the Error-shape
validation so plain objects like { constructor: { kind: 'X' } } no longer pass.

Signed-off-by: Kenton Duprey <kenton@clerk.dev>
@kduprey kduprey merged commit 97c9ab3 into main Dec 19, 2025
42 checks passed
@kduprey kduprey deleted the kenton/port-7490-to-core-3 branch December 19, 2025 18:02
Sign up for free to 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