Skip to content

feat(clerk-js,clerk-react,types): Update signal hooks to always return values #6605

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 3 commits into
base: main
Choose a base branch
from

Conversation

dstaley
Copy link
Member

@dstaley dstaley commented Aug 21, 2025

…n values

Description

This PR updates our Signal implementation to ensure that a value is always returned, especially when accessed via IsomorphicClerk before clerk-js has loaded. This is achieved with a new StateProxy class instance that will intercept method calls and wait for clerk-js to be loaded before calling them, in addition to returning sane default values. When clerk-js is loaded, the __internal_state property of IsomorphicClerk switches to the clerkjs.__internal_state property, bypassing the StateProxy.

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

    • Sign-in and sign-up signals are now always available (no null returns).
    • finalize() in sign-in/up flows accepts no arguments for simpler usage.
  • Refactor

    • Internal clerk state now consistently available across environments, improving pre-load behavior of auth flows.
  • Chores

    • Bumped minor versions of multiple packages.
    • Experimental note: removal of the isLoaded flag from signals.

Copy link

vercel bot commented Aug 21, 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 Aug 22, 2025 8:50pm

Copy link

pkg-pr-new bot commented Aug 21, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 20a720c

Copy link
Contributor

coderabbitai bot commented Aug 21, 2025

📝 Walkthrough

Walkthrough

The diff makes Clerk internals non-nullable: __internal_state is now always present and sign-in/sign-up signals and their __internal_future resources are non-null. SignIn/SignUp classes set __internal_future to concrete futures and their finalize methods accept an optional params object. React hooks and isomorphic APIs were updated to return non-null signal/state types. A new StateProxy provides a concrete State before ClerkJS loads. New type additions include SignInFutureResource and SignUpFutureResource. A changeset file for minor package bumps was added.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 6db7ec3 and 20a720c.

📒 Files selected for processing (1)
  • packages/react/src/stateProxy.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/react/src/stateProxy.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). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan

🪧 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 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

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/types/src/signUp.ts (1)

1-1: Use a relative path for the PhoneCodeChannel import

The type PhoneCodeChannel is declared in packages/types/src/phoneCodeChannel.ts, so importing it as a bare module will fail. Update the import in your signUp.ts accordingly:

• File: packages/types/src/signUp.ts (line 1)
Apply this diff:

-import type { PhoneCodeChannel } from 'phoneCodeChannel';
+import type { PhoneCodeChannel } from './phoneCodeChannel';
🧹 Nitpick comments (13)
.changeset/rotten-falcons-cover.md (1)

1-7: Expand the changeset notes to capture the API surface changes and add a brief migration snippet

The current note only mentions the experimental removal of Signals isLoaded, but this PR also:

  • Makes Clerk.__internal_state non-null (via StateProxy pre-load),
  • Makes SignIn.__internal_future and SignUp.__internal_future non-null,
  • Allows calling finalize() with no args on both futures,
  • Ensures React hooks return non-null signals.

Capturing these points will help consumers understand the impact and how to migrate.

Apply this diff to augment the changeset body:

 ---
 '@clerk/clerk-js': minor
 '@clerk/clerk-react': minor
 '@clerk/types': minor
 ---
 
-[Experimental] Signals `isLoaded` removal
+[Experimental] Signals `isLoaded` removal
+
+- Clerk: `__internal_state` is now always defined (non-null). Before ClerkJS is ready, a lightweight StateProxy provides sensible defaults; once ready, it switches to the real State.
+- ClerkJS: `SignIn.__internal_future` and `SignUp.__internal_future` are now always present (non-null).
+- ClerkJS: `SignInFuture.finalize()` and `SignUpFuture.finalize()` can be called without arguments.
+- React: Signal hooks now return non-null signal objects.
+
+Migration:
+- Remove conditional guards for `isLoaded` on signals; the returned objects are always present.
+- Stop checking `Clerk.__internal_state` for null/undefined; it is always available.
+- Calling `finalize()` without arguments is now supported; pass `{ navigate }` only when you need custom navigation.
packages/types/src/clerk.ts (1)

233-239: Document the new non-null guarantee for __internal_state

Since __internal_state is now always defined and backed by a StateProxy pre-load, the JSDoc should reflect the non-null guarantee and briefly explain the behavior to reduce confusion.

   /**
-   * @experimental This experimental API is subject to change.
-   *
-   * Entrypoint for Clerk's Signal API containing resource signals along with accessible versions of `computed()` and
-   * `effect()` that can be used to subscribe to changes from Signals.
+   * @experimental This experimental API is subject to change.
+   *
+   * Entrypoint for Clerk's Signal API containing resource signals, plus `computed()` and `effect()` helpers.
+   * This property is always defined. Before ClerkJS is ready, it is backed by an internal StateProxy that
+   * provides sensible defaults and forwards calls once ClerkJS has loaded.
    */
   __internal_state: State;
packages/types/src/signIn.ts (2)

127-132: Make __internal_future read-only in the public type

This property is initialized once per resource and should not be reassigned by consumers. Marking it readonly communicates intent and helps with type safety.

   /**
    * @internal
    */
-  __internal_future: SignInFutureResource;
+  readonly __internal_future: SignInFutureResource;

159-160: Add null to the finalize signature for JS null-safety

A quick search for finalize(null) returned no hits, so there are no internal call sites relying on passing null. It’s safe to expand the signature to accommodate JS consumers and avoid a potential destructuring TypeError at runtime.

• File: packages/types/src/signIn.ts
Lines: 159–160
Update the finalize declaration:

-  finalize: (params?: { navigate?: SetActiveNavigate }) => Promise<{ error: unknown }>;
+  finalize: (params?: { navigate?: SetActiveNavigate } | null) => Promise<{ error: unknown }>;
packages/clerk-js/src/core/resources/SignIn.ts (2)

94-95: Mark __internal_future as readonly

This future instance is conceptually immutable per SignIn instance. Marking it readonly prevents accidental reassignment and matches the public type suggestion.

-  __internal_future: SignInFuture = new SignInFuture(this);
+  readonly __internal_future: SignInFuture = new SignInFuture(this);

641-649: Harden finalize against null params from JS callers

Current destructuring with a default value throws if null is passed. This change is harmless for TS and more robust for JS.

-  async finalize({ navigate }: { navigate?: SetActiveNavigate } = {}): Promise<{ error: unknown }> {
+  async finalize(params?: { navigate?: SetActiveNavigate } | null): Promise<{ error: unknown }> {
+    const navigate = params?.navigate;
     return runAsyncResourceTask(this.resource, async () => {
       if (!this.resource.createdSessionId) {
         throw new Error('Cannot finalize sign-in without a created session.');
       }
 
       await SignIn.clerk.setActive({ session: this.resource.createdSessionId, navigate });
     });
   }

Happy to add targeted tests for:

  • Calling __internal_future.finalize() with undefined and with { navigate },
  • Error path when createdSessionId is missing,
  • Ensuring __internal_future is always present on a fresh SignIn instance.
packages/clerk-js/src/core/resources/SignUp.ts (2)

90-91: Mark __internal_future as readonly

Same rationale as SignIn: the future should be immutable after construction.

-  __internal_future: SignUpFuture = new SignUpFuture(this);
+  readonly __internal_future: SignUpFuture = new SignUpFuture(this);

542-550: Null-safe finalize for JS callers and parity with SignIn

Avoid runtime errors on finalize(null) from JS. This mirrors the suggested hardening for SignInFuture.

-  async finalize({ navigate }: { navigate?: SetActiveNavigate } = {}): Promise<{ error: unknown }> {
+  async finalize(params?: { navigate?: SetActiveNavigate } | null): Promise<{ error: unknown }> {
+    const navigate = params?.navigate;
     return runAsyncResourceTask(this.resource, async () => {
       if (!this.resource.createdSessionId) {
         throw new Error('Cannot finalize sign-up without a created session.');
       }
 
       await SignUp.clerk.setActive({ session: this.resource.createdSessionId, navigate });
     });
   }

I can also add tests that assert:

  • finalize() works without args and with { navigate },
  • Error thrown when createdSessionId is absent,
  • __internal_future is always defined on a fresh SignUp.
packages/types/src/signUp.ts (1)

121-125: Consider making __internal_future readonly.
The property reference itself should not change after initialization; the underlying resource can mutate. Marking it readonly improves type safety.

-  __internal_future: SignUpFutureResource;
+  readonly __internal_future: SignUpFutureResource;
packages/react/src/hooks/useClerkSignal.ts (3)

24-31: Subscribe when not loaded: proactively listen for status to avoid missing the transition.
Today, when clerk.loaded === false, subscribe returns a noop and re-subscribes later via a new callback identity. That works but is brittle. Prefer subscribing to the status event and invoking callback() upon ready, guaranteeing useSyncExternalStore updates exactly when Clerk loads.

   const subscribe = useCallback(
     (callback: () => void) => {
-      if (!clerk.loaded) {
-        return () => {};
-      }
-
-      return clerk.__internal_state.__internal_effect(() => {
+      if (!clerk.loaded) {
+        const unsubscribe = clerk.on('status', s => {
+          if (s === 'ready') {
+            unsubscribe();
+            callback();
+          }
+        });
+        return unsubscribe;
+      }
+
+      return clerk.__internal_state.__internal_effect(() => {
         switch (signal) {
           case 'signIn':
             clerk.__internal_state.signInSignal();
             break;
           case 'signUp':
             clerk.__internal_state.signUpSignal();
             break;
           default:
             throw new Error(`Unknown signal: ${signal}`);
         }
         callback();
       });
     },
     [clerk, clerk.loaded, clerk.__internal_state],
   );

Also applies to: 33-37


17-20: Add JSDoc for public hook overloads.
Per guidelines, public APIs should have JSDoc. Briefly document that the hook returns non-null reactive signal objects even before Clerk loads (backed by StateProxy).

-function useClerkSignal(signal: 'signIn'): NonNullSignInSignal;
+/**
+ * Returns a non-null, reactive SignIn signal backed by a proxy until Clerk loads.
+ */
+function useClerkSignal(signal: 'signIn'): NonNullSignInSignal;
-function useClerkSignal(signal: 'signUp'): NonNullSignUpSignal;
+/**
+ * Returns a non-null, reactive SignUp signal backed by a proxy until Clerk loads.
+ */
+function useClerkSignal(signal: 'signUp'): NonNullSignUpSignal;

1-69: Please add tests for the new non-null contract.

  • Preload scenario: before Clerk loads, useClerkSignal('signIn'|'signUp') returns objects with errors, fetchStatus, and callable methods that don't throw on access.
  • Transition scenario: after simulating Clerk load, the hook reflects real state and methods delegate to ClerkJS.
  • SSR safety: server-render path should not invoke proxy methods; ensure snapshots render without throwing.

I can draft RTL/Jest tests for the hook with a mocked IsomorphicClerk and a fake StateProxy. Want me to push a test file?

packages/react/src/stateProxy.ts (1)

22-34: Document StateProxy as internal and its guarantees.
Add a brief JSDoc stating that it:

  • Implements State
  • Returns stable object identities per accessor
  • Defers method invocations until Clerk is loaded
  • Throws meaningful errors in unsupported environments
-export class StateProxy implements State {
+/**
+ * @internal
+ * A lightweight proxy implementing Clerk `State` that exposes stable signal objects and
+ * defers method calls until ClerkJS is loaded.
+ */
+export class StateProxy implements State {
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

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

📒 Files selected for processing (9)
  • .changeset/rotten-falcons-cover.md (1 hunks)
  • packages/clerk-js/src/core/resources/SignIn.ts (2 hunks)
  • packages/clerk-js/src/core/resources/SignUp.ts (2 hunks)
  • packages/react/src/hooks/useClerkSignal.ts (2 hunks)
  • packages/react/src/isomorphicClerk.ts (4 hunks)
  • packages/react/src/stateProxy.ts (1 hunks)
  • packages/types/src/clerk.ts (1 hunks)
  • packages/types/src/signIn.ts (2 hunks)
  • packages/types/src/signUp.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
.changeset/**

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

Automated releases must use Changesets.

Files:

  • .changeset/rotten-falcons-cover.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/types/src/clerk.ts
  • packages/types/src/signIn.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/react/src/stateProxy.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/types/src/signUp.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/types/src/clerk.ts
  • packages/types/src/signIn.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/react/src/stateProxy.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/types/src/signUp.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/types/src/clerk.ts
  • packages/types/src/signIn.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/react/src/stateProxy.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/types/src/signUp.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/types/src/clerk.ts
  • packages/types/src/signIn.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/react/src/stateProxy.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/types/src/signUp.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/types/src/clerk.ts
  • packages/types/src/signIn.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/react/src/stateProxy.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/types/src/signUp.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/types/src/clerk.ts
  • packages/types/src/signIn.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/react/src/stateProxy.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/types/src/signUp.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/types/src/clerk.ts
  • packages/types/src/signIn.ts
  • packages/react/src/isomorphicClerk.ts
  • packages/clerk-js/src/core/resources/SignUp.ts
  • packages/react/src/stateProxy.ts
  • packages/clerk-js/src/core/resources/SignIn.ts
  • packages/react/src/hooks/useClerkSignal.ts
  • packages/types/src/signUp.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). (6)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (8)
packages/types/src/signUp.ts (2)

121-125: Internal future on SignUpResource aligns with runtime; good addition.
This makes the API shape consistent with ClerkJS and enables gating via proxies.


135-136: Optional finalize params: aligns types with runtime defaults.
This change unblocks calling finalize() without args. Please ensure related JSDoc mentions the default navigation behavior when params are omitted.

Would you like me to update/add JSDoc snippets in both @clerk/types and clerk-js to document the default behavior?

packages/react/src/isomorphicClerk.ts (2)

59-59: StateProxy integration looks correct.
Import, field declaration, and constructor initialization are straightforward and side-effect free.

Also applies to: 162-162, 255-256


729-731: Non-null __internal_state with fallback is the right call.
Returning clerkjs.__internal_state when loaded and a StateProxy otherwise satisfies the new non-null contract for hooks and consumers.

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

7-16: Non-null signal types are well-formed.
The Omit + NonNullable pattern cleanly removes nullability from signIn/signUp while preserving the rest of the shape.


49-52: Snapshot reads against non-null state are correct.
Directly reading the signals from __internal_state matches the new contract and avoids unsafe non-null assertions.

packages/react/src/stateProxy.ts (2)

78-83: Explicit errors for internal reactivity APIs pre-load are acceptable.
Throwing on __internal_effect/__internal_computed before load is fine given the hook prevents these paths until loaded === true.


35-75: Default signal shapes: verify parity with ClerkJS to avoid shape drift.
Ensure status literals and method keys match ClerkJS’ runtime signals (needs_identifier, missing_requirements, availableStrategies, nested emailCode/resetPasswordEmailCode APIs). If ClerkJS changes, this proxy should be updated in lockstep.

I can add a small type-level test that asserts StateProxy['signInSignal']() satisfies ReturnType<LoadedClerk['__internal_state']['signInSignal']> to catch drift at compile time. Want me to add it?

Copy link

changeset-bot bot commented Aug 21, 2025

🦋 Changeset detected

Latest commit: 20a720c

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

♻️ Duplicate comments (1)
packages/react/src/stateProxy.ts (1)

96-101: SSR hang resolved — gated methods now fail fast off-browser.

Good job addressing the prior SSR hang by checking inBrowser() before awaiting addOnLoaded. This prevents unresolved promises during SSR. Nothing else needed here.

🧹 Nitpick comments (7)
packages/react/src/stateProxy.ts (7)

99-101: Optional: add a timeout guard around addOnLoaded to avoid edge-case deadlocks.

If ClerkJS fails to load (network, CSP, ad blockers), awaiting addOnLoaded can still hang indefinitely in the browser. Consider a short timeout with an actionable error.

-      if (!this.isomorphicClerk.loaded) {
-        await new Promise<void>(resolve => this.isomorphicClerk.addOnLoaded(resolve));
-      }
+      if (!this.isomorphicClerk.loaded) {
+        const timeoutMs = 10_000;
+        await Promise.race([
+          new Promise<void>(resolve => this.isomorphicClerk.addOnLoaded(resolve)),
+          new Promise<void>((_, reject) =>
+            setTimeout(
+              () =>
+                reject(
+                  new Error(
+                    `Clerk did not load within ${timeoutMs}ms. Verify that <ClerkProvider> is mounted and ClerkJS is reachable.`,
+                  ),
+                ),
+              timeoutMs,
+            ),
+          ),
+        ]);
+      }

93-105: Tighten gateMethod typing to match original return shape and avoid double-wrapped Promises.

Using Promise<ReturnType<F>> can become Promise<Promise<R>> when F already returns a Promise (very likely here). Prefer Awaited<ReturnType<F>> to preserve the original function’s surface type.

   private gateMethod<T extends object, K extends keyof T & string>(getTarget: () => T, key: K) {
-    type F = Extract<T[K], (...args: unknown[]) => unknown>;
-    return (async (...args: Parameters<F>): Promise<ReturnType<F>> => {
+    type F = Extract<T[K], (...args: unknown[]) => unknown>;
+    return (async (...args: Parameters<F>): Promise<Awaited<ReturnType<F>>> => {
       if (!inBrowser()) {
         return errorThrower.throw(`Attempted to call a method (${key}) that is not supported on the server.`);
       }
       if (!this.isomorphicClerk.loaded) {
         await new Promise<void>(resolve => this.isomorphicClerk.addOnLoaded(resolve));
       }
       const t = getTarget();
       return (t[key] as (...args: Parameters<F>) => ReturnType<F>).apply(t, args);
-    }) as F;
+    }) as F;
   }

27-35: Add explicit return types and mark public API surface explicitly.

Per guidelines, explicitly annotate return types for public methods and type the cached proxies accordingly.

-  private readonly signInSignalProxy = this.buildSignInProxy();
-  private readonly signUpSignalProxy = this.buildSignUpProxy();
+  private readonly signInSignalProxy: ReturnType<State['signInSignal']> = this.buildSignInProxy();
+  private readonly signUpSignalProxy: ReturnType<State['signUpSignal']> = this.buildSignUpProxy();

-  signInSignal() {
+  public signInSignal(): ReturnType<State['signInSignal']> {
     return this.signInSignalProxy;
   }
-  signUpSignal() {
+  public signUpSignal(): ReturnType<State['signUpSignal']> {
     return this.signUpSignalProxy;
   }

37-61: Annotate helper builders’ return types to lock API shape to State.

This makes it harder for accidental structural drift to creep in and improves editor IntelliSense.

-  private buildSignInProxy() {
+  private buildSignInProxy(): ReturnType<State['signInSignal']> {
     const target = () => this.client.signIn.__internal_future;
@@
-    return {
+    return {
       errors: defaultErrors(),
       fetchStatus: 'idle' as const,
       signIn: {
         status: 'needs_identifier' as const,
         availableStrategies: [],
@@
-    };
+    } as ReturnType<State['signInSignal']>;
   }
@@
-  private buildSignUpProxy() {
+  private buildSignUpProxy(): ReturnType<State['signUpSignal']> {
     const target = () => this.client.signUp.__internal_future;
@@
-    return {
+    return {
       errors: defaultErrors(),
       fetchStatus: 'idle' as const,
       signUp: {
         status: 'missing_requirements' as const,
         unverifiedFields: [],
@@
-    };
+    } as ReturnType<State['signUpSignal']>;
   }

Also applies to: 62-78


80-85: Unify error handling and make messages actionable for devs.

Use the shared errorThrower for consistent error formatting, and include recovery suggestions.

-  __internal_effect(_: () => void): () => void {
-    throw new Error('__internal_effect called before Clerk is loaded');
-  }
-  __internal_computed<T>(_: (prev?: T) => T): () => T {
-    throw new Error('__internal_computed called before Clerk is loaded');
-  }
+  __internal_effect(_: () => void): () => void {
+    errorThrower.throw(
+      '__internal_effect called before Clerk is loaded. Call this only in the browser after Clerk has loaded.',
+    );
+  }
+  __internal_computed<T>(_: (prev?: T) => T): () => T {
+    errorThrower.throw(
+      '__internal_computed called before Clerk is loaded. Call this only in the browser after Clerk has loaded.',
+    );
+  }

87-91: Improve the client-not-ready error with context and guidance.

The current message is terse. Provide actionable context to reduce support load.

-    if (!c) throw new Error('Clerk client not ready');
+    if (!c) {
+      throw new Error(
+        'Clerk client is not ready. If you are on the server, avoid calling State methods; otherwise, wait for Clerk to load (e.g., add a loaded listener or use the provided gated methods).',
+      );
+    }

24-35: Please add tests for proxy defaults, SSR gating, and handoff to real state.

Given the behavioral changes, unit/integration tests will help prevent regressions:

  • SSR: calling any gated method should throw immediately with a helpful message.
  • Browser, before load: methods should wait until addOnLoaded resolves, then delegate to ClerkJS.
  • Defaults: signInSignal()/signUpSignal() should return stable default shapes (errors structure, fetchStatus, status).
  • Handoff: after load, ensure calls bypass the proxy and hit clerkjs.__internal_state.
  • Error propagation: downstream errors from ClerkJS methods are surfaced unchanged through the proxy.

Would you like me to scaffold Jest tests that mock IsomorphicClerk.addOnLoaded, loaded, and client to cover these cases?

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • 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 11e8cba and 6db7ec3.

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

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

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

Files:

  • packages/react/src/stateProxy.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/react/src/stateProxy.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/react/src/stateProxy.ts
packages/**/*.{ts,tsx,d.ts}

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

Packages should export TypeScript types alongside runtime code

Files:

  • packages/react/src/stateProxy.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/react/src/stateProxy.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/react/src/stateProxy.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/react/src/stateProxy.ts
🧬 Code graph analysis (1)
packages/react/src/stateProxy.ts (3)
packages/types/src/state.ts (1)
  • Errors (23-27)
packages/react/src/isomorphicClerk.ts (1)
  • IsomorphicClerk (117-1420)
packages/clerk-js/src/utils/runtime.ts (1)
  • inBrowser (1-3)
🪛 ESLint
packages/react/src/stateProxy.ts

[error] 1-5: Run autofix to sort these imports!

(simple-import-sort/imports)


[error] 4-4: '@clerk/shared' import is restricted from being used. Please always import from '@clerk/shared/' instead of '@clerk/shared'.

(no-restricted-imports)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: Build Packages
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep/ci
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan

@@ -151,7 +156,7 @@ export interface SignInFutureResource {
redirectUrl: string;
redirectUrlComplete: string;
}) => Promise<{ error: unknown }>;
finalize: (params: { navigate?: SetActiveNavigate }) => Promise<{ error: unknown }>;
finalize: (params?: { navigate?: SetActiveNavigate }) => Promise<{ error: unknown }>;
Copy link
Member

Choose a reason for hiding this comment

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

👍🏻

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.

3 participants