-
Notifications
You must be signed in to change notification settings - Fork 402
fix(clerk-react): Correct useAuth().isLoaded in transitive state #7157
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
🦋 Changeset detectedLatest commit: 0f3f02f The changes in this PR will be included in the next version bump. This PR includes changesets to release 8 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 |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughModify useAuth to select auth context based on isomorphicClerk.isLoaded; add a test that asserts useAuth returns isLoaded = false when isomorphicClerk is loaded but in a transitive state; add a patch changeset for Changes
Sequence Diagram(s)sequenceDiagram
participant Component
participant useAuth
participant ISC as IsomorphicClerk
participant AuthCtx as AuthContext
participant Helpers as getToken/signOut
Component->>useAuth: invoke hook
useAuth->>ISC: read isLoaded
ISC-->>useAuth: isLoaded flag
alt ISC not loaded OR transitive
useAuth->>AuthCtx: use initialAuthState (report isLoaded=false)
note right of AuthCtx `#f0f0f0`: no session/user IDs
useAuth-->>Component: return derived auth (isLoaded=false, undefined ids)
else ISC ready
useAuth->>AuthCtx: use existing authContext
useAuth->>Helpers: create helpers with ISC
Helpers-->>useAuth: helper functions
useAuth-->>Component: return derived auth (isLoaded=true, populated ids)
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20–30 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (3 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 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). (5)
Comment |
|
!snapshot |
|
Hey @jacekradko - the snapshot version command generated the following package versions:
Tip: Use the snippet copy button below to quickly install the required packages. npm i @clerk/agent-toolkit@0.1.47-snapshot.v20251105162613 --save-exact
npm i @clerk/astro@2.14.5-snapshot.v20251105162613 --save-exact
npm i @clerk/backend@2.19.4-snapshot.v20251105162613 --save-exact
npm i @clerk/chrome-extension@2.7.13-snapshot.v20251105162613 --save-exact
npm i @clerk/clerk-js@5.104.1-snapshot.v20251105162613 --save-exact
npm i @clerk/elements@0.23.78-snapshot.v20251105162613 --save-exact
npm i @clerk/clerk-expo@2.18.2-snapshot.v20251105162613 --save-exact
npm i @clerk/expo-passkeys@0.4.15-snapshot.v20251105162613 --save-exact
npm i @clerk/express@1.7.46-snapshot.v20251105162613 --save-exact
npm i @clerk/fastify@2.5.3-snapshot.v20251105162613 --save-exact
npm i @clerk/localizations@3.26.7-snapshot.v20251105162613 --save-exact
npm i @clerk/nextjs@6.34.4-snapshot.v20251105162613 --save-exact
npm i @clerk/nuxt@1.11.5-snapshot.v20251105162613 --save-exact
npm i @clerk/clerk-react@5.53.7-snapshot.v20251105162613 --save-exact
npm i @clerk/react-router@2.1.9-snapshot.v20251105162613 --save-exact
npm i @clerk/remix@4.13.12-snapshot.v20251105162613 --save-exact
npm i @clerk/shared@3.31.1-snapshot.v20251105162613 --save-exact
npm i @clerk/tanstack-react-start@0.26.8-snapshot.v20251105162613 --save-exact
npm i @clerk/testing@1.13.12-snapshot.v20251105162613 --save-exact
npm i @clerk/themes@2.4.33-snapshot.v20251105162613 --save-exact
npm i @clerk/types@4.97.2-snapshot.v20251105162613 --save-exact
npm i @clerk/vue@1.14.12-snapshot.v20251105162613 --save-exact |
@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: |
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: 0
🧹 Nitpick comments (2)
packages/react/src/hooks/useAuth.ts (2)
105-107: Verify the guard logic with integration tests.The updated condition correctly handles the transitive state by resetting
authContextonly when Clerk is not loaded AND bothsessionIdanduserIdare undefined. This ensuresisLoadedreturnsfalseduring the loading phase.However, the actual logic change in
useAuthis not directly covered by integration tests. Consider adding test cases that specifically verifyuseAuthbehavior with differentisomorphicClerk.loadedvalues:
- When
isomorphicClerk.loaded = falsewith no auth data → should return not loaded- When
isomorphicClerk.loaded = truewith no auth data → should return loaded but not signed in- When
isomorphicClerk.loaded = falsebut auth data exists (SSR scenario) → should use the auth dataWould you like me to generate test cases that cover these scenarios?
98-99: Consider replacingas anywith proper typing.The
as anytype assertion bypasses TypeScript's type safety. Consider usingunknownwith type guards or defining an explicit type forinitialAuthState.const { treatPendingAsSignedOut, ...rest } = initialAuthStateOrOptions ?? {}; - const initialAuthState = rest as any; + const initialAuthState = rest as unknown;Alternatively, define a proper interface for the expected shape of
initialAuthState.As per coding guidelines.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
packages/react/src/hooks/__tests__/useAuth.test.tsx(1 hunks)packages/react/src/hooks/useAuth.ts(1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/hooks/__tests__/useAuth.test.tsxpackages/react/src/hooks/useAuth.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/hooks/__tests__/useAuth.test.tsxpackages/react/src/hooks/useAuth.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsxpackages/react/src/hooks/useAuth.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/hooks/__tests__/useAuth.test.tsxpackages/react/src/hooks/useAuth.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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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 assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/hooks/__tests__/useAuth.test.tsxpackages/react/src/hooks/useAuth.ts
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.{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/hooks/__tests__/useAuth.test.tsxpackages/react/src/hooks/useAuth.ts
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.test.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
🧬 Code graph analysis (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx (1)
packages/react/src/hooks/useAuth.ts (1)
useDerivedAuth(152-194)
⏰ 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: triage
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
packages/react/src/hooks/useAuth.ts (2)
102-102: LGTM: Early initialization improves clarity.Initializing
isomorphicClerkearly makes the dependency explicit and enables its use in the guard condition below.
109-110: LGTM: Correct usage of early-initialized variable.Using the early-initialized
isomorphicClerkeliminates the need for redeclaration and improves code organization.packages/react/src/hooks/__tests__/useAuth.test.tsx (1)
321-345: Valid test for transitive state with partial initialization.This test extends coverage by validating that when an auth object has methods (
signOut,getToken) but incomplete data fields (undefinedsessionId,userId),isLoadedcorrectly returnsfalse. This represents a realistic transitive state where the Clerk instance exists but authentication data is still loading.The test differs meaningfully from the existing test at lines 87-102 by explicitly setting multiple fields and including methods, rather than using an empty object.
Note: This test validates
useDerivedAuthbehavior. The actual fix inuseAuth.ts(line 105 checkingisomorphicClerk.loaded) would benefit from additional integration tests as mentioned in the previous review comment.
This comment has been minimized.
This comment has been minimized.
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: 0
🧹 Nitpick comments (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx (1)
82-85: Consider improving mock type safety.The mock uses
as anytype assertion which bypasses TypeScript's type checking. For better type safety, consider using a more specific type:- const mockIsomorphicClerk = { + const mockIsomorphicClerk: Partial<LoadedClerk> = { loaded: true, telemetry: { record: vi.fn() }, };And update the provider:
- <ClerkInstanceContext.Provider value={{ value: mockIsomorphicClerk as any }}> + <ClerkInstanceContext.Provider value={{ value: mockIsomorphicClerk as LoadedClerk }}>Also applies to: 102-102
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx(1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/hooks/__tests__/useAuth.test.tsx
**/*.{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/hooks/__tests__/useAuth.test.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.{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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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 assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/hooks/__tests__/useAuth.test.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.{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/hooks/__tests__/useAuth.test.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.test.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
🧬 Code graph analysis (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx (2)
packages/react/src/hooks/useAuth.ts (1)
useAuth(95-124)packages/react/src/contexts/AuthContext.ts (1)
AuthContext(23-23)
⏰ 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: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx (1)
81-112: Test correctly validates transitive state behavior.The test properly verifies that
useAuth()returnsisLoaded: falsewhen the Clerk SDK is loaded but the auth state is in a transitive (undetermined) state with undefinedsessionIdanduserId. The test structure follows established patterns and React Testing Library best practices.
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: 0
🧹 Nitpick comments (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx (1)
81-112: Test correctly verifies the transitive state fix.The test logic is sound and properly validates the PR's objective: when
isomorphicClerkis loaded but the auth context contains undefined values (transitive state),useAuth()should returnisLoaded: false. The mock setup and assertions accurately reflect this scenario.Consider extracting mock creation to typed factory functions to improve type safety and reusability:
const createMockIsomorphicClerk = (overrides?: Partial<LoadedClerk>): LoadedClerk => ({ loaded: true, telemetry: { record: vi.fn() }, // ... other required LoadedClerk properties with sensible defaults ...overrides, } as LoadedClerk); const createMockAuthContext = (overrides?: Partial<AuthContextValue>): AuthContextValue => ({ actor: undefined, factorVerificationAge: null, orgId: undefined, orgPermissions: undefined, orgRole: undefined, orgSlug: undefined, sessionClaims: null, sessionId: undefined, sessionStatus: undefined, userId: undefined, ...overrides, } as AuthContextValue);Then use them in the test:
- const mockIsomorphicClerk = { - loaded: true, - telemetry: { record: vi.fn() }, - }; - - const mockAuthContext = { - actor: undefined, - factorVerificationAge: null, - orgId: undefined, - orgPermissions: undefined, - orgRole: undefined, - orgSlug: undefined, - sessionClaims: null, - sessionId: undefined, - sessionStatus: undefined, - userId: undefined, - }; + const mockIsomorphicClerk = createMockIsomorphicClerk({ loaded: true }); + const mockAuthContext = createMockAuthContext();This approach follows the guideline to "create type-safe test builders/factories" and reduces the use of
as anycasts.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx(1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{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/hooks/__tests__/useAuth.test.tsx
**/*.{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/hooks/__tests__/useAuth.test.tsx
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.{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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor 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 assertionsfor literal types:as const
Usesatisfiesoperator 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 ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor 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/hooks/__tests__/useAuth.test.tsx
**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{jsx,tsx}: Use error boundaries in React components
Minimize re-renders in React components
**/*.{jsx,tsx}: Always use functional components with hooks instead of class components
Follow PascalCase naming for components:UserProfile,NavigationMenu
Keep components focused on a single responsibility - split large components
Limit component size to 150-200 lines; extract logic into custom hooks
Use composition over inheritance - prefer smaller, composable components
Export components as named exports for better tree-shaking
One component per file with matching filename and component name
Use useState for simple state management
Use useReducer for complex state logic
Implement proper state initialization
Use proper state updates with callbacks
Implement proper state cleanup
Use Context API for theme/authentication
Implement proper state selectors
Use proper state normalization
Implement proper state persistence
Use React.memo for expensive components
Implement proper useCallback for handlers
Use proper useMemo for expensive computations
Implement proper virtualization for lists
Use proper code splitting with React.lazy
Implement proper cleanup in useEffect
Use proper refs for DOM access
Implement proper event listener cleanup
Use proper abort controllers for fetch
Implement proper subscription cleanup
Use proper HTML elements
Implement proper ARIA attributes
Use proper heading hierarchy
Implement proper form labels
Use proper button types
Implement proper focus management
Use proper keyboard shortcuts
Implement proper tab order
Use proper skip links
Implement proper focus traps
Implement proper error boundaries
Use proper error logging
Implement proper error recovery
Use proper error messages
Implement proper error fallbacks
Use proper form validation
Implement proper error states
Use proper error messages
Implement proper form submission
Use proper form reset
Use proper component naming
Implement proper file naming
Use proper prop naming
Implement proper...
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.{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/hooks/__tests__/useAuth.test.tsx
**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.tsx: Use proper type definitions for props and state
Leverage TypeScript's type inference where possible
Use proper event types for handlers
Implement proper generic types for reusable components
Use proper type guards for conditional rendering
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/*.test.{jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/react.mdc)
**/*.test.{jsx,tsx}: Use React Testing Library
Test component behavior, not implementation
Use proper test queries
Implement proper test isolation
Use proper test coverage
Test component interactions
Use proper test data
Implement proper test setup
Use proper test cleanup
Implement proper test assertions
Use proper test structure
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/react/src/hooks/__tests__/useAuth.test.tsx
🧬 Code graph analysis (1)
packages/react/src/hooks/__tests__/useAuth.test.tsx (3)
packages/clerk-js/src/test/utils.ts (1)
renderHook(77-77)packages/react/src/hooks/useAuth.ts (1)
useAuth(95-120)packages/react/src/contexts/AuthContext.ts (1)
AuthContext(23-23)
⏰ 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: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
This comment has been minimized.
This comment has been minimized.
| if (authContext.sessionId === undefined && authContext.userId === undefined) { | ||
| authContext = initialAuthState != null ? initialAuthState : {}; | ||
| } |
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.
Oh, so previously it was falling back to the initial auth state when sessionId and userId was undefined? This was likely fine in CSR apps as the initial state there would be isLoading: true, but not so fine in SSRd apps.
I think you might have stumbled on the root cause of the sign in bug here too! When signing in, the initial state would be sessionId: null, user is signed out. When sign in transitions to the transitive state, sessionId and userId becomes undefined, so this would fall back to the initial state, which is null.
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.
| } | ||
|
|
||
| const isomorphicClerk = useIsomorphicClerkContext(); | ||
| const authContext = !isomorphicClerk.loaded && initialAuthState ? initialAuthState : authContextFromHook; |
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.
This is a separate existing issue, but since you are touching the code I thought I might comment on it in context, not suggesting we tackle it here since it's a bigger one.
With SSR, initialAuthState is always what will have been used. With this code, if Clerk has loaded before this part of the application has hydrated (selective hydration can defer hydrating Suspense boundaries), this would use the hook state, which might differ from the initialAuthState, causing hydration mismatches. This is probably most likely with static SSR builds.
The canonical fix would be to use useSyncExternalStore and pass the initial state to the getServerSnapshot function. Since we are using context here there's nothing to subscribe to though, so not sure how that plays out.
We also can't use useSyncExternalStore in the ClerkProvider (where we do listen to the Clerk store), since that wouldn't work with selective hydration, it would only use getServerSnapshot when that part of the application was hydrating.

Description
When isomorphicClerk is loaded, we should return
isLoaded: falsefromuseAuth()when transitive state is set.The check ensures we only override auth state with initial values when Clerk SDK hasn't loaded yet. Once loaded, we respect the actual auth state, even if it's transitioning, so components know to wait until session data is fully resolved.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Tests
Chores