Skip to content

feat(clerk-js,clerk-react,types): Signal errors #6495

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

dstaley
Copy link
Member

@dstaley dstaley commented Aug 8, 2025

Description

This PR adds error parsing to our Signals implementation, which is still internal, and not intended for public consumption (yet!).

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

  • New Features

    • Improved error handling during sign-in by providing detailed, field-specific error messages and global errors.
    • Enhanced error parsing for sign-in responses, enabling clearer feedback on issues like invalid credentials or missing fields.
  • Bug Fixes

    • Updated error types throughout the sign-in process for more consistent and predictable error reporting.
  • Documentation

    • Added a changeset entry outlining the introduction of an experimental feature related to "Signal Errors."

Copy link

changeset-bot bot commented Aug 8, 2025

🦋 Changeset detected

Latest commit: 837fdc2

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

This PR includes changesets to release 22 packages
Name Type
@clerk/clerk-js Minor
@clerk/clerk-react Minor
@clerk/types Minor
@clerk/chrome-extension Patch
@clerk/clerk-expo Patch
@clerk/elements Patch
@clerk/nextjs Patch
@clerk/react-router Patch
@clerk/remix Patch
@clerk/tanstack-react-start Patch
@clerk/agent-toolkit Patch
@clerk/astro Patch
@clerk/backend Patch
@clerk/expo-passkeys Patch
@clerk/express Patch
@clerk/fastify Patch
@clerk/localizations Patch
@clerk/nuxt Patch
@clerk/shared Patch
@clerk/testing Patch
@clerk/themes 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

Copy link

vercel bot commented Aug 8, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
clerk-js-sandbox ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 8, 2025 7:40pm

Copy link

pkg-pr-new bot commented Aug 8, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 837fdc2

Copy link
Contributor

coderabbitai bot commented Aug 8, 2025

📝 Walkthrough

Walkthrough

This change set introduces a more structured and type-safe approach to error handling within the sign-in flow of the codebase. It updates the error payload types across several modules, replacing generic or unknown error types with the specific ClerkAPIResponseError type. A new function is added to parse API errors into a structured Errors object with field-specific and global error categorization. Type definitions are enhanced in the types package to reflect these changes, including the introduction of FieldError, FieldErrors, and Errors interfaces. Minor version updates are documented in a new changeset file. No core logic or control flow is altered beyond error typing and parsing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~15–20 minutes

Complexity label: Moderate
This review involves several medium-complexity changes, including type signature updates, new structured error parsing logic, and updates to public type declarations. The changes are confined to error handling and type safety, without affecting broader application logic or introducing extensive new functionality.

Note

🔌 MCP (Model Context Protocol) integration is now available in Early Access!

Pro users can now connect to remote MCP servers under the Integrations page to get reviews and chat conversations that understand additional development context.


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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: 6

🧹 Nitpick comments (6)
.changeset/happy-dodos-sneeze.md (1)

7-7: Clarify experimental scope in the changeset body

Consider adding a short one-liner clarifying that Signal Errors are internal-only and subject to change, plus a brief summary of what “error parsing” covers (API errors into field/global categories).

packages/react/src/hooks/useClerkSignal.ts (1)

49-51: Add minimal JSDoc for experimental surface

Mark useSignInSignal as experimental/internal to set expectations for consumers.

/**
 * @experimental Internal API subject to change.
 * Returns the sign-in signal snapshot (or null on init).
 */
packages/clerk-js/src/core/state.ts (1)

22-25: Correctly forward typed API errors to the signal

This aligns the state with the event payload. Consider adding tests to ensure:

  • Non-API errors clear the error signal
  • API-shaped errors are parsed into field/global buckets by the computed signal

Would you like me to draft unit tests for these two cases?

packages/clerk-js/src/core/signals.ts (2)

40-41: Shadowed variable name hinders readability

The arrow-function parameter error shadows the outer error parameter. Rename one of them (err / apiErr, etc.) to make the control flow clearer and prevent accidental misuse.


22-38: Consider data-driven mapping instead of long switch

The repetitive switch can be replaced by a simple lookup table to reduce maintenance overhead and avoid missing future fields:

const map: Record<string, keyof Errors['fields']> = {
  first_name: 'firstName',
  last_name: 'lastName',
  email_address: 'emailAddress',
  identifier: 'identifier',
  phone_number: 'phoneNumber',
  password: 'password',
  username: 'username',
  code: 'code',
  captcha: 'captcha',
  legal_accepted: 'legalAccepted',
};

error?.errors.forEach(e => {
  const key = map[e.meta?.paramName as string];
  key ? (parsedErrors.fields[key] = e) : parsedErrors.global.push(e);
});

Cleaner, faster, and harder to get out of sync with types.

packages/types/src/state.ts (1)

22-26: Prefer precise types over any[] for raw and global

Both arrays hold API error objects, so typing them as any[] discards useful information. Suggest tightening to the actual Clerk error shape:

-  raw: any[];
-  global: any[];
+  raw: ClerkAPIResponseError['errors'];
+  global: ClerkAPIResponseError['errors'];

(or a reusable type APIError = ClerkAPIResponseError['errors'][number]).

Improves IntelliSense and guards against accidental misuse.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cf284ee and 837fdc2.

📒 Files selected for processing (7)
  • .changeset/happy-dodos-sneeze.md (1 hunks)
  • packages/clerk-js/src/core/events.ts (2 hunks)
  • packages/clerk-js/src/core/resources/SignIn.ts (4 hunks)
  • packages/clerk-js/src/core/signals.ts (1 hunks)
  • packages/clerk-js/src/core/state.ts (2 hunks)
  • packages/react/src/hooks/useClerkSignal.ts (1 hunks)
  • packages/types/src/state.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Automated releases must use Changesets.

Files:

  • .changeset/happy-dodos-sneeze.md
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/events.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/clerk-js/src/core/state.ts
  • packages/clerk-js/src/core/signals.ts
  • packages/types/src/state.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use Prettier for consistent code formatting

Files:

  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/events.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/clerk-js/src/core/state.ts
  • packages/clerk-js/src/core/signals.ts
  • packages/types/src/state.ts
packages/**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/events.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/clerk-js/src/core/state.ts
  • packages/clerk-js/src/core/signals.ts
  • packages/types/src/state.ts
packages/**/*.{ts,tsx,d.ts}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Packages should export TypeScript types alongside runtime code

Files:

  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/events.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/clerk-js/src/core/state.ts
  • packages/clerk-js/src/core/signals.ts
  • packages/types/src/state.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/development.mdc)

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
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
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/events.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/clerk-js/src/core/state.ts
  • packages/clerk-js/src/core/signals.ts
  • packages/types/src/state.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/monorepo.mdc)

Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.

Files:

  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/events.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/clerk-js/src/core/state.ts
  • packages/clerk-js/src/core/signals.ts
  • packages/types/src/state.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.

Files:

  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/clerk-js/src/core/events.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/clerk-js/src/core/state.ts
  • packages/clerk-js/src/core/signals.ts
  • packages/types/src/state.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
.changeset/happy-dodos-sneeze.md (1)

1-5: Appropriate changeset scope and bump levels

Minor bumps across JS, React, and Types make sense given additive typing and internal signal changes.

packages/clerk-js/src/core/events.ts (1)

17-17: Type the error payload as ClerkAPIResponseError | null — LGTM

The typed payload will help downstream consumers and aligns with the parsing work.

packages/clerk-js/src/core/resources/SignIn.ts (1)

15-15: Importing ClerkAPIResponseError for error typing — OK

This aligns with the event payload typing across the codebase.

packages/clerk-js/src/core/state.ts (1)

1-1: Type-only import for ClerkAPIResponseError — LGTM

Keeps runtime clean and matches the new payload typing.

@@ -1,5 +1,5 @@
import { createEventBus } from '@clerk/shared/eventBus';
import type { TokenResource } from '@clerk/types';
import type { ClerkAPIResponseError, TokenResource } from '@clerk/types';
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify all emitters conform to the new payload

Now that ResourceErrorPayload.error is ClerkAPIResponseError | null, ensure all eventBus.emit('resource:error', …) sites either pass a properly typed API error or null (for non-API errors).

Run this to find non-conforming emitters:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "All resource:error emit sites:"
rg -n "eventBus\\.emit\\('resource:error'" -A 3 -B 1

echo
echo "Emitters that don't cast/guard to ClerkAPIResponseError or null:"
rg -n "eventBus\\.emit\\('resource:error', \\{[^}]*error: (?!null)(?!\\(.*ClerkAPIResponseError\\)).*\\}" -U || true

Length of output: 5359


Ensure all resource:error emits use ClerkAPIResponseError | null

A couple of eventBus.emit('resource:error', …) calls are still passing the raw err (type unknown) instead of casting it to ClerkAPIResponseError. Please update them to match the new payload type:

• packages/clerk-js/src/core/resources/SignIn.ts

  • Line 522
  • Line 535

Change each instance from:

eventBus.emit('resource:error', { resource: this.resource, error: err });

to:

eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });

This ensures ResourceErrorPayload.error is always ClerkAPIResponseError or null.

🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts at lines 522 and 535, the
eventBus.emit calls for 'resource:error' are passing the error as type unknown
instead of ClerkAPIResponseError. Update these calls by casting the error to
ClerkAPIResponseError using 'err as ClerkAPIResponseError' to ensure the emitted
payload matches the expected type ClerkAPIResponseError | null.

Comment on lines 560 to 563
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
return { error: err };
}
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

Avoid unsound cast; guard before emitting API error

err here can be a locally thrown Error (e.g., “Email code factor not found”). Blindly casting to ClerkAPIResponseError risks runtime shape errors down the line. Guard, and emit null for non-API errors.

Apply:

-      eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
+      const apiErr = isClerkAPIResponseError(err) ? err : null;
+      eventBus.emit('resource:error', { resource: this.resource, error: apiErr });

Add this helper (once per module or in a shared util):

// Type guard for API errors
function isClerkAPIResponseError(err: unknown): err is ClerkAPIResponseError {
  return !!err && typeof err === 'object' && Array.isArray((err as any).errors);
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 560 to 563, the
error object `err` is unsafely cast to `ClerkAPIResponseError` without checking
its type, which can cause runtime errors. To fix this, implement a type guard
function `isClerkAPIResponseError` that checks if `err` has the expected shape
(e.g., an `errors` array). Use this guard before emitting the error event: emit
the error only if it passes the guard, otherwise emit null or handle
accordingly. This prevents unsafe casts and ensures only valid API errors are
emitted.

Comment on lines 575 to 578
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
return { error: err };
}
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

Same guard needed here

Don’t cast arbitrary errors to ClerkAPIResponseError; guard and emit null when not API-shaped.

-      eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
+      const apiErr = isClerkAPIResponseError(err) ? err : null;
+      eventBus.emit('resource:error', { resource: this.resource, error: apiErr });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
return { error: err };
}
} catch (err: unknown) {
const apiErr = isClerkAPIResponseError(err) ? err : null;
eventBus.emit('resource:error', { resource: this.resource, error: apiErr });
return { error: err };
}
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 575 to 578, the
catch block casts any caught error to ClerkAPIResponseError without verifying
its shape. To fix this, add a type guard to check if the error matches the
ClerkAPIResponseError structure before emitting it; if it does not, emit null
instead. Also, update the returned error accordingly to avoid unsafe casting.

Comment on lines 615 to 617
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
return { error: err };
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

Guard before emitting in SSO flow

This path throws local errors (e.g., “modal flow is not supported yet”). Use the same guard to avoid mis-typing the signal.

-      eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
+      const apiErr = isClerkAPIResponseError(err) ? err : null;
+      eventBus.emit('resource:error', { resource: this.resource, error: apiErr });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} catch (err: unknown) {
eventBus.emit('resource:error', { resource: this.resource, error: err });
eventBus.emit('resource:error', { resource: this.resource, error: err as ClerkAPIResponseError });
return { error: err };
} catch (err: unknown) {
const apiErr = isClerkAPIResponseError(err) ? err : null;
eventBus.emit('resource:error', { resource: this.resource, error: apiErr });
return { error: err };
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/resources/SignIn.ts around lines 615 to 617, the
catch block emits an error event without checking if the current flow supports
it, which can cause issues with local errors like "modal flow is not supported
yet." Add a guard condition before emitting the 'resource:error' event to ensure
it only emits for supported flows, preventing mis-typing or inappropriate signal
emission.

Comment on lines +40 to +77
error?.errors.forEach(error => {
if ('meta' in error && error.meta && 'paramName' in error.meta) {
switch (error.meta.paramName) {
case 'first_name':
parsedErrors.fields.firstName = error;
break;
case 'last_name':
parsedErrors.fields.lastName = error;
break;
case 'email_address':
parsedErrors.fields.emailAddress = error;
break;
case 'identifier':
parsedErrors.fields.identifier = error;
break;
case 'phone_number':
parsedErrors.fields.phoneNumber = error;
break;
case 'password':
parsedErrors.fields.password = error;
break;
case 'username':
parsedErrors.fields.username = error;
break;
case 'code':
parsedErrors.fields.code = error;
break;
case 'captcha':
parsedErrors.fields.captcha = error;
break;
case 'legal_accepted':
parsedErrors.fields.legalAccepted = error;
break;
}
} else {
parsedErrors.global.push(error);
}
});
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

Unhandled paramName values silently drop errors

If the API returns a field error whose paramName is not covered by the switch, the error is neither assigned to a field nor pushed to global, so it disappears from the parsed result. Add a default branch (or fall-through handling) that routes unknown field names to parsedErrors.global to avoid information loss.

-      switch (error.meta.paramName) {
+      switch (error.meta.paramName) {
         ...
-        case 'legal_accepted':
-          parsedErrors.fields.legalAccepted = error;
-          break;
+        case 'legal_accepted':
+          parsedErrors.fields.legalAccepted = error;
+          break;
+        default:
+          parsedErrors.global.push(error);
+          break;
       }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
error?.errors.forEach(error => {
if ('meta' in error && error.meta && 'paramName' in error.meta) {
switch (error.meta.paramName) {
case 'first_name':
parsedErrors.fields.firstName = error;
break;
case 'last_name':
parsedErrors.fields.lastName = error;
break;
case 'email_address':
parsedErrors.fields.emailAddress = error;
break;
case 'identifier':
parsedErrors.fields.identifier = error;
break;
case 'phone_number':
parsedErrors.fields.phoneNumber = error;
break;
case 'password':
parsedErrors.fields.password = error;
break;
case 'username':
parsedErrors.fields.username = error;
break;
case 'code':
parsedErrors.fields.code = error;
break;
case 'captcha':
parsedErrors.fields.captcha = error;
break;
case 'legal_accepted':
parsedErrors.fields.legalAccepted = error;
break;
}
} else {
parsedErrors.global.push(error);
}
});
error?.errors.forEach(error => {
if ('meta' in error && error.meta && 'paramName' in error.meta) {
switch (error.meta.paramName) {
case 'first_name':
parsedErrors.fields.firstName = error;
break;
case 'last_name':
parsedErrors.fields.lastName = error;
break;
case 'email_address':
parsedErrors.fields.emailAddress = error;
break;
case 'identifier':
parsedErrors.fields.identifier = error;
break;
case 'phone_number':
parsedErrors.fields.phoneNumber = error;
break;
case 'password':
parsedErrors.fields.password = error;
break;
case 'username':
parsedErrors.fields.username = error;
break;
case 'code':
parsedErrors.fields.code = error;
break;
case 'captcha':
parsedErrors.fields.captcha = error;
break;
case 'legal_accepted':
parsedErrors.fields.legalAccepted = error;
break;
default:
parsedErrors.global.push(error);
break;
}
} else {
parsedErrors.global.push(error);
}
});
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/signals.ts between lines 40 and 77, the switch
statement handling error.meta.paramName does not account for unknown paramName
values, causing those errors to be dropped silently. Add a default case to the
switch that pushes any unrecognized errors to parsedErrors.global to ensure no
errors are lost.

import { useCallback, useSyncExternalStore } from 'react';

import { useIsomorphicClerkContext } from '../contexts/IsomorphicClerkContext';
import { useAssertWrappedByClerkProvider } from './useAssertWrappedByClerkProvider';

function useClerkSignal(signal: 'signIn'): { errors: unknown; signIn: SignInFutureResource | null } | null {
function useClerkSignal(signal: 'signIn') {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Restore explicit return types for public APIs

Per guidelines, exported hooks should have explicit return types. You can capture the core’s type without duplicating shapes via ReturnType of the State['signInSignal'].

+import type { State as ClerkState } from '@clerk/types';
 
-function useClerkSignal(signal: 'signIn') {
+function useClerkSignal(signal: 'signIn'): ReturnType<ClerkState['signInSignal']> | null {
   …
 }
 
-export function useSignInSignal() {
+export function useSignInSignal(): ReturnType<ClerkState['signInSignal']> | null {
   return useClerkSignal('signIn');
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function useClerkSignal(signal: 'signIn') {
// Add the type import
import type { State as ClerkState } from '@clerk/types';
function useClerkSignal(
signal: 'signIn'
): ReturnType<ClerkState['signInSignal']> | null {
}
export function useSignInSignal(): ReturnType<ClerkState['signInSignal']> | null {
return useClerkSignal('signIn');
}
🤖 Prompt for AI Agents
In packages/react/src/hooks/useClerkSignal.ts at line 6, the exported hook
useClerkSignal lacks an explicit return type. Fix this by adding an explicit
return type using ReturnType<typeof State['signInSignal']> to capture the core
type without duplicating shapes, ensuring the public API follows the guidelines.

@dstaley dstaley changed the title feat(clerk-js,react,types): Signal errors feat(clerk-js,clerk-react,types): Signal errors Aug 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants