Skip to content

Conversation

nikosdouvlis
Copy link
Member

@nikosdouvlis nikosdouvlis commented Sep 1, 2025

Description

errors.global can now be used without checking for the .length property:

if (errors.global) {
   return <div>{errors.global[0].message}</div>
}

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

  • Bug Fixes

    • Improved reliability of error handling to prevent rare crashes when processing unexpected error formats.
    • Ensured global and raw error lists are created only when needed, avoiding edge-case failures.
  • Refactor

    • Streamlined error parsing logic for greater robustness and consistency across error scenarios.
    • Optimized error-handling paths to reduce unnecessary allocations during processing.

Copy link

changeset-bot bot commented Sep 1, 2025

🦋 Changeset detected

Latest commit: e644e1f

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

This PR includes changesets to release 0 packages

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

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 Sep 1, 2025

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

Project Deployment Preview Comments Updated (UTC)
clerk-js-sandbox Ready Ready Preview Comment Sep 2, 2025 8:21am

Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

Walkthrough

Parsed error collections raw and global are now nullable and lazily initialized; parsing logic in clerk-js assigns singleton arrays for non-Clerk errors and conditionally creates/pushes into raw/global. The Errors interface types were updated to unknown[] | null. A placeholder changeset file was added.

Changes

Cohort / File(s) Summary
Error parsing logic
packages/clerk-js/src/core/signals.ts
Change parsing to make parsedErrors.raw and parsedErrors.global nullable and lazily initialized; set singleton arrays for non-Clerk errors; remove bulk spread push; per-error processing now conditionally initializes arrays before pushing; field mapping via meta.paramName retained.
Types update
packages/types/src/state.ts
Errors interface updated: raw and global types changed from unknown[] to `unknown[]
Changeset
.changeset/red-tools-eat.md
Add new changeset placeholder file with minimal content.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant Parser as parseErrors()
  Caller->>Parser: parseErrors(error)
  alt Not a Clerk API error
    note over Parser: lazy init singleton arrays
    Parser->>Parser: parsedErrors.raw = [error]
    Parser->>Parser: parsedErrors.global = [error]
  else Clerk API error with errors[]
    loop For each item in error.errors
      alt item.meta.paramName present
        Parser->>Parser: Map item to fields[item.meta.paramName]
      end
      alt parsedErrors.global exists
        Parser->>Parser: parsedErrors.global.push(item)
      else
        Parser->>Parser: parsedErrors.global = [item]
      end
      alt parsedErrors.raw exists
        Parser->>Parser: parsedErrors.raw.push(item)
      else
        Parser->>Parser: parsedErrors.raw = [item]
      end
    end
  end
  Parser-->>Caller: parsedErrors (raw/global may be null)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I thump my paws at errors’ call,
Now null or arrays—I'll catch them all.
With lazy nests for bugs to land,
I sort the storms with steady hand.
A hop, a push, or none at all—
Clean fields, calm logs, and carrot haul. 🥕

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch nikos/change-global-errors-type

🪧 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.
    • 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.
  • 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 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/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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

pkg-pr-new bot commented Sep 1, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: e644e1f

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

🧹 Nitpick comments (3)
packages/types/src/state.ts (1)

25-26: Document new nullability on public API.

Add JSDoc so integrators know to guard with a truthy check instead of .length.

Apply:

 export interface Errors {
   fields: FieldErrors;
-  raw: unknown[] | null;
-  global: unknown[] | null;
+  /** Null when there are no raw errors. Prefer `if (errors.raw)` over checking `.length`. */
+  raw: unknown[] | null;
+  /** Null when there are no global errors. Prefer `if (errors.global)` over checking `.length`. */
+  global: unknown[] | null;
 }
packages/clerk-js/src/core/signals.ts (2)

70-75: Condense lazy initialization and avoid shadowing.

Use nullish-assignment to remove duplication and rename the loop variable to prevent shadowing the outer error.

Apply:

-  error.errors.forEach(error => {
-    if (parsedErrors.raw) {
-      parsedErrors.raw.push(error);
-    } else {
-      parsedErrors.raw = [error];
-    }
+  error.errors.forEach(apiError => {
+    (parsedErrors.raw ??= []).push(apiError);
 
-    if ('meta' in error && error.meta && 'paramName' in error.meta) {
-      const name = snakeToCamel(error.meta.paramName);
-      parsedErrors.fields[name as keyof typeof parsedErrors.fields] = error;
+    if ('meta' in apiError && apiError.meta && 'paramName' in apiError.meta) {
+      const name = snakeToCamel(apiError.meta.paramName);
+      parsedErrors.fields[name as keyof typeof parsedErrors.fields] = apiError;
       return;
     }
 
-    if (parsedErrors.global) {
-      parsedErrors.global.push(error);
-    } else {
-      parsedErrors.global = [error];
-    }
+    (parsedErrors.global ??= []).push(apiError);
   });

Also applies to: 82-86


76-80: Guard unknown param names to avoid writing outside known fields.

If snakeToCamel(paramName) doesn’t match FieldErrors keys, fall back to global.

Apply:

-    if ('meta' in apiError && apiError.meta && 'paramName' in apiError.meta) {
-      const name = snakeToCamel(apiError.meta.paramName);
-      parsedErrors.fields[name as keyof typeof parsedErrors.fields] = apiError;
-      return;
-    }
+    if ('meta' in apiError && apiError.meta && 'paramName' in apiError.meta) {
+      const name = snakeToCamel(apiError.meta.paramName);
+      if (name && (name in parsedErrors.fields)) {
+        parsedErrors.fields[name as keyof typeof parsedErrors.fields] = apiError;
+        return;
+      }
+    }

Also applies to: 82-86

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 a50cfc8 and f2affab.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/signals.ts (1 hunks)
  • packages/types/src/state.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/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/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/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/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/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/signals.ts
  • packages/types/src/state.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/signals.ts (1)
packages/shared/src/underscore.ts (1)
  • snakeToCamel (51-53)
⏰ 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). (6)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
packages/types/src/state.ts (2)

25-26: Change aligns types with runtime (nullable raw/global).

This matches the lazy initialization in clerk-js and enables simple truthy checks by consumers.


25-26: No actionable call‐site changes needed.
Searches for errors.global.length, errors.raw.length, optional‐chained/non‐null‐asserted .length, and direct indexing returned no matches—there are no existing call sites to update.

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

55-57: Initialize to null to match updated types.

Correctly mirrors Errors nullability.


64-66: Non-API errors routed to raw/global as singletons.

Good default; avoids empty arrays and keeps semantics consistent.

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • 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 f2affab and e644e1f.

📒 Files selected for processing (1)
  • .changeset/red-tools-eat.md (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/red-tools-eat.md
🪛 LanguageTool
.changeset/red-tools-eat.md

[grammar] ~1-~1: Hier könnte ein Fehler sein.
Context: --- ---

(QB_NEW_DE)

⏰ 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). (23)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (tanstack-react-router, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome)
  • GitHub Check: Static analysis
  • GitHub Check: Unit Tests (18, --filter=@clerk/astro --filter=@clerk/backend --filter=@clerk/express --filter=@c...
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

Comment on lines +1 to +2
---
---
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

Changeset is empty/invalid — specify package bumps and summary.

Without valid frontmatter, CI release won’t pick this up. Given errors.raw/global can now be null at runtime and in types, this is plausibly a breaking change for TS consumers; consider a major bump (or confirm desired semver).

Apply this diff (adjust semver if you decide it’s minor/patch):

---- 
----
+---
+"@clerk/clerk-js": major
+"@clerk/types": major
+---
+
+Make `Errors.raw` and `Errors.global` nullable (`unknown[] | null`) and lazily initialized in clerk-js parsing.
+
+BREAKING (types/runtime): Code assuming arrays must now handle `null`.
+Migration:
+```ts
+if (errors.global) {
+  render(errors.global[0]?.message);
+}
+// or
+for (const e of errors.raw ?? []) { /* ... */ }
+```

🏁 Script executed:

#!/bin/bash

# Inspect the changeset file for missing frontmatter
cat .changeset/red-tools-eat.md

Length of output: 41


Populate .changeset/red-tools-eat.md frontmatter
The file currently contains only empty markers; add valid package bumps and a summary so CI can detect this breaking change. Since errors.raw/errors.global now allow null, this warrants a major bump (or confirm the desired semver).

---- 
----
+---
+"@clerk/clerk-js": major
+"@clerk/types": major
+---
+
+Make `Errors.raw` and `Errors.global` nullable (`unknown[] | null`) and lazily initialized in clerk-js parsing.
+
+BREAKING (types/runtime): Code assuming arrays must now handle `null`.
+Migration:
+```ts
+if (errors.global) {
+  render(errors.global[0]?.message);
+}
+// or
+for (const e of errors.raw ?? []) { /* ... */ }
+```
🧰 Tools
🪛 LanguageTool

[grammar] ~1-~1: Hier könnte ein Fehler sein.
Context: --- ---

(QB_NEW_DE)

🤖 Prompt for AI Agents
In .changeset/red-tools-eat.md around lines 1 to 2, the file contains only empty
markers and needs valid Changeset frontmatter so CI recognizes the release;
replace the empty frontmatter with a YAML block listing the affected package(s)
and their bump type (use "major" because errors.raw/errors.global now accept
null), and add a short summary sentence describing the breaking change (mention
errors.raw/errors.global allowing null and recommended migration notes). Ensure
the file has the standard three-dash delimiters, a "packages:" mapping with the
package names and "major" as the bump, and a non-empty body paragraph explaining
the change.

Copy link
Member

@panteliselef panteliselef left a comment

Choose a reason for hiding this comment

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

Let's verify if an empty changeset is appropriate.

@nikosdouvlis nikosdouvlis requested a review from dstaley September 2, 2025 14:10
@@ -52,30 +52,38 @@ function errorsToParsedErrors(error: unknown): Errors {
captcha: null,
legalAccepted: null,
},
raw: [],
global: [],
raw: null,
Copy link
Member

Choose a reason for hiding this comment

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

I hate that this is the case, but we need to update the default errors in the state proxy in clerk-react as well 😭

Copy link
Member Author

Choose a reason for hiding this comment

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

Good catch!
Ill try to prioritize some tests to catch these sooner and a (potential) refactor later. Fixing...

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.

4 participants