-
Notifications
You must be signed in to change notification settings - Fork 377
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
base: main
Are you sure you want to change the base?
Conversation
The latest updates on your projects. Learn more about Vercel for GitHub.
|
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
📝 WalkthroughWalkthroughThe 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 detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ 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)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 importThe type
PhoneCodeChannel
is declared inpackages/types/src/phoneCodeChannel.ts
, so importing it as a bare module will fail. Update the import in yoursignUp.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 snippetThe 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
andSignUp.__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 typeThis 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
: Addnull
to thefinalize
signature for JS null-safetyA quick search for
finalize(null)
returned no hits, so there are no internal call sites relying on passingnull
. 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 thefinalize
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
asreadonly
This future instance is conceptually immutable per
SignIn
instance. Marking itreadonly
prevents accidental reassignment and matches the public type suggestion.- __internal_future: SignInFuture = new SignInFuture(this); + readonly __internal_future: SignInFuture = new SignInFuture(this);
641-649
: Hardenfinalize
againstnull
params from JS callersCurrent 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 freshSignIn
instance.packages/clerk-js/src/core/resources/SignUp.ts (2)
90-91
: Mark__internal_future
asreadonly
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-safefinalize
for JS callers and parity with SignInAvoid runtime errors on
finalize(null)
from JS. This mirrors the suggested hardening forSignInFuture
.- 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 freshSignUp
.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 itreadonly
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, whenclerk.loaded === false
,subscribe
returns a noop and re-subscribes later via a new callback identity. That works but is brittle. Prefer subscribing to thestatus
event and invokingcallback()
uponready
, guaranteeinguseSyncExternalStore
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 witherrors
,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 fakeStateProxy
. 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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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
: Optionalfinalize
params: aligns types with runtime defaults.
This change unblocks callingfinalize()
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
andclerk-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.
Returningclerkjs.__internal_state
when loaded and aStateProxy
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.
TheOmit
+NonNullable
pattern cleanly removes nullability fromsignIn/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 untilloaded === true
.
35-75
: Default signal shapes: verify parity with ClerkJS to avoid shape drift.
Ensurestatus
literals and method keys match ClerkJS’ runtime signals (needs_identifier
,missing_requirements
,availableStrategies
, nestedemailCode/resetPasswordEmailCode
APIs). If ClerkJS changes, this proxy should be updated in lockstep.I can add a small type-level test that asserts
StateProxy['signInSignal']()
satisfiesReturnType<LoadedClerk['__internal_state']['signInSignal']>
to catch drift at compile time. Want me to add it?
🦋 Changeset detectedLatest commit: 20a720c The changes in this PR will be included in the next version bump. This PR includes changesets to release 22 packages
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 |
There was a problem hiding this 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 awaitingaddOnLoaded
. 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 becomePromise<Promise<R>>
whenF
already returns a Promise (very likely here). PreferAwaited<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
, andclient
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.
📒 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
Avoidany
type - preferunknown
when type is uncertain, then narrow with type guards
Useinterface
for object shapes that might be extended
Usetype
for unions, primitives, and computed types
Preferreadonly
properties for immutable data structures
Useprivate
for internal implementation details
Useprotected
for inheritance hierarchies
Usepublic
explicitly for clarity in public APIs
Preferreadonly
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
Useconst assertions
for literal types:as const
Usesatisfies
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 ...
Noany
types without justification
Proper error handling with typed errors
Consistent use ofreadonly
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 }>; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍🏻
…n values
Description
This PR updates our Signal implementation to ensure that a value is always returned, especially when accessed via
IsomorphicClerk
beforeclerk-js
has loaded. This is achieved with a newStateProxy
class instance that will intercept method calls and wait forclerk-js
to be loaded before calling them, in addition to returning sane default values. Whenclerk-js
is loaded, the__internal_state
property ofIsomorphicClerk
switches to theclerkjs.__internal_state
property, bypassing theStateProxy
.Checklist
pnpm test
runs as expected.pnpm build
runs as expected.Type of change
Summary by CodeRabbit
New Features
Refactor
Chores