- 
                Notifications
    
You must be signed in to change notification settings  - Fork 402
 
fix(clerk-js): Ensure sessionId is set after sign in #7117
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. 
  | 
    
          
WalkthroughsetActive now avoids transitive updates for pending or identical sessions; updateClient applies an initial session on first and subsequent client assignments; initialization bootstraps a preliminary client/session from a JWT cookie before attempting the network fetch and on certain fetch failures. Changes
 Sequence Diagram(s)sequenceDiagram
    participant Init as Init flow
    participant Cookie as JWT Cookie
    participant PreClient as Preliminary Client
    participant Fetch as Network Fetch
    participant Client as Final Client
    participant State as Session State
    Note over Init,Cookie: pre-populate from cookie before network fetch
    Cookie->>PreClient: derive client/session (if JWT present)
    PreClient->>State: updateClient(preliminaryClient) -> apply initial session/accessors
    Init->>Fetch: async request final client
    Fetch->>Client: return full client
    Client->>State: updateClient(finalClient) -> reconcile sessions
    sequenceDiagram
    participant Caller as Caller
    participant Clerk as ClerkCore
    participant State as SessionState
    Note over Caller,Clerk: condensed setActive flow
    Caller->>Clerk: setActive(newSession, options)
    alt newSession is pending
        Clerk->>State: skip transitive update
    else newSession differs or org switch requested
        Clerk->>State: perform transitive update (apply accessors)
    else
        Clerk->>State: no-op (avoid redundant reset)
    end
    Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes 
 Poem
 Pre-merge checks and finishing touches✅ Passed checks (2 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). (22)
 Comment   | 
    
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
📜 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/clerk-js/src/core/clerk.ts(4 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/core/clerk.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/core/clerk.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/clerk-js/src/core/clerk.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/clerk.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/clerk.ts (2)
packages/react/src/isomorphicClerk.ts (1)
session(682-688)packages/clerk-js/src/core/jwt-client.ts (1)
createClientFromJwt(19-100)
🔇 Additional comments (2)
packages/clerk-js/src/core/clerk.ts (2)
1415-1417: Nice guard against redundant transitive clearsSkipping the transitive reset when we’re navigating with the same or a pending session keeps
sessionIdstable through the redirect and directly addresses the regression. Well done.
2601-2605: Preloading from the cookie is a solid improvementHydrating from the JWT before the
/clientfetch lands removes the visible gap wheresessionIdwasnullon the next page. This sequencing change makes the whole flow feel instant.
        
          
                packages/clerk-js/src/core/clerk.ts
              
                Outdated
          
        
      | } | ||
| 
               | 
          ||
| if (newSession?.status !== 'pending') { | ||
| if (newSession?.status !== 'pending' && this.session?.id !== newSession?.id) { | 
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.
we want the transitive state to work when switching between orgs, doesn't this affect that since sessionId will remain the same in that scenario
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.
Yeah, I believe that is correct. This logic does not account for switching orgs. 🤔
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.
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.
Do we know how the transitive state cause a null ? Because it usually means undefined is emitted
| const jwtInCookie = this.#authService?.getSessionCookie(); | ||
| if (jwtInCookie) { | ||
| const preliminaryClient = createClientFromJwt(jwtInCookie); | ||
| this.updateClient(preliminaryClient); | ||
| } | ||
| 
               | 
          ||
| return Client.getOrCreateInstance() | ||
| .fetch() | ||
| .then(res => this.updateClient(res)) | 
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.
Could this cause a mismatch for a couple of seconds? Let's say that the client from the session cookie has certain user attributes, but once it gets the latest one from FAPI, then it updates some properties
          
@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:   | 
    
| 
          
 Found 45 test failures on Blacksmith runners: 
  | 
    
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
📜 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/clerk-js/src/core/clerk.ts(4 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/core/clerk.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/clerk.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/core/clerk.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/clerk-js/src/core/clerk.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/clerk.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/clerk.ts (2)
packages/react/src/isomorphicClerk.ts (1)
session(682-688)packages/clerk-js/src/core/jwt-client.ts (1)
createClientFromJwt(19-100)
⏰ 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). (4)
- GitHub Check: Formatting | Dedupe | Changeset
 - GitHub Check: Analyze (javascript-typescript)
 - GitHub Check: semgrep-cloud-platform/scan
 - GitHub Check: semgrep-cloud-platform/scan
 
🔇 Additional comments (2)
packages/clerk-js/src/core/clerk.ts (2)
2601-2605: State listeners are notified twice during initialization, creating a brief window of inconsistent client state.The
updateClientmethod (line 2353) calls#emit()at line 2393 every time it's invoked. During initialization, this occurs twice in rapid succession:
- Line 2604:
 updateClient(preliminaryClient)from JWT cookie →#emit()notifies listeners- Line 2609:
 updateClient(res)from FAPI fetch →#emit()notifies listenersThis creates a brief period where listeners and components observe stale user attributes from the JWT before the authoritative FAPI response arrives. UI components reading client state during this window may render outdated information, then update again moments later when the FAPI response completes.
To mitigate this, consider:
- Adding an optional parameter to
 updateClientto suppress#emit()during preliminary population:updateClient(client, { emit: false })- Only emit after the FAPI response settles, not after the intermediate JWT-based state
 
1415-1417: The organization change will be reflected in the UI.Upon reviewing the code flow, the concern in the original review comment is incorrect. While the guard at line 1415 prevents
setTransitiveState()from being called for pending sessions during organization switches, this does not prevent the organization state from being updated.The key is that
setAccessors(newSession)is called unconditionally at line 1444, which reconstructs the organization from the updatedlastActiveOrganizationId. ThesetTransitiveState()method only temporarily clears state (session/org/user) for UI flicker prevention—it does not control state propagation. Therefore, organization changes are properly reflected in the UI regardless of the pending session status.Likely an incorrect or invalid review 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.45-snapshot.v20251103041116 --save-exact
 npm i @clerk/astro@2.14.3-snapshot.v20251103041116 --save-exact
 npm i @clerk/backend@2.19.2-snapshot.v20251103041116 --save-exact
 npm i @clerk/chrome-extension@2.7.11-snapshot.v20251103041116 --save-exact
 npm i @clerk/clerk-js@5.103.2-snapshot.v20251103041116 --save-exact
 npm i @clerk/elements@0.23.76-snapshot.v20251103041116 --save-exact
 npm i @clerk/clerk-expo@2.17.4-snapshot.v20251103041116 --save-exact
 npm i @clerk/expo-passkeys@0.4.13-snapshot.v20251103041116 --save-exact
 npm i @clerk/express@1.7.44-snapshot.v20251103041116 --save-exact
 npm i @clerk/fastify@2.5.1-snapshot.v20251103041116 --save-exact
 npm i @clerk/localizations@3.26.5-snapshot.v20251103041116 --save-exact
 npm i @clerk/nextjs@6.34.2-snapshot.v20251103041116 --save-exact
 npm i @clerk/nuxt@1.11.3-snapshot.v20251103041116 --save-exact
 npm i @clerk/clerk-react@5.53.5-snapshot.v20251103041116 --save-exact
 npm i @clerk/react-router@2.1.7-snapshot.v20251103041116 --save-exact
 npm i @clerk/remix@4.13.10-snapshot.v20251103041116 --save-exact
 npm i @clerk/shared@3.30.0-snapshot.v20251103041116 --save-exact
 npm i @clerk/tanstack-react-start@0.26.6-snapshot.v20251103041116 --save-exact
 npm i @clerk/testing@1.13.10-snapshot.v20251103041116 --save-exact
 npm i @clerk/themes@2.4.31-snapshot.v20251103041116 --save-exact
 npm i @clerk/types@4.97.0-snapshot.v20251103041116 --save-exact
 npm i @clerk/vue@1.14.10-snapshot.v20251103041116 --save-exact | 
    
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.
It seems like there are three distinct fixes here, is there one of the three that fixes the root issue?
| const jwtInCookie = this.#authService?.getSessionCookie(); | ||
| if (jwtInCookie) { | ||
| const preliminaryClient = createClientFromJwt(jwtInCookie); | ||
| this.updateClient(preliminaryClient); | ||
| } | 
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.
Why is this necessary? clerk shouldn't be considered loaded until the client is loaded, in which case the session should already be set.
| } else if (!isFirstClientSet && newClient.sessions?.length > 0) { | ||
| const session = this.#options.selectInitialSession | ||
| ? this.#options.selectInitialSession(newClient) | ||
| : this.#defaultSession(newClient); | ||
| this.#setAccessors(session); | 
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.
do we know why this is new case is necessary? The client is being updated, which has a new session to be set, but the session accessor wasn't yet set elsewhere?
| } | ||
| 
               | 
          ||
| if (newSession?.status !== 'pending') { | ||
| if (newSession?.status !== 'pending' && (this.session?.id !== newSession?.id || shouldSwitchOrganization)) { | 
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.
what problem is this addressing? The transitive state sets undefined, not null. If we're not entirely sure,  I would recommend that we remove this.
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 unclear to me as well. Could this cause a chain of events that result to null eventually ?
Description
Initial attempt to resolve the sessionID being null immediately after signing in and navigating to the next route.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
Performance Improvements
Reliability