Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Oct 31, 2025

Description

After signing in and navigating, users briefly saw a null session (sessionId: null) before the correct session appeared. This change addresses this in 2 ways:

  • Prevent unnecessary session clearing in updateClient() if session_id wasn't changing
  • Handle the race condition where session.touch() would trigger an updateClient() prior to setActive() finishing it's business

Fixes: USER-3877

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

  • Performance Improvements

    • Avoids unnecessary session state updates when the active session is unchanged or pending.
    • Pre-populates in-memory client/session state earlier to speed startup and reduce stale-session workarounds.
  • Reliability / Bug Fixes

    • Applies the active session immediately after sign-in and when a new client with sessions is detected, improving session consistency.
  • Tests

    • Adds tests for session update behavior during navigation and after sign-in.
  • Chores

    • Adds a patch changeset noting the session timing fix.

@changeset-bot
Copy link

changeset-bot bot commented Oct 31, 2025

🦋 Changeset detected

Latest commit: 51b2f6a

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

This PR includes changesets to release 3 packages
Name Type
@clerk/clerk-js Patch
@clerk/chrome-extension Patch
@clerk/clerk-expo 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

@vercel
Copy link

vercel bot commented Oct 31, 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 Nov 4, 2025 7:39pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 31, 2025

Walkthrough

setActive now only triggers transitive state updates for non-pending sessions when the active session actually changes or an organization switch is requested. updateClient now derives and applies an initial session/accessors immediately on first client assignment and when a later client with sessions arrives, aligning in-memory state.

Changes

Cohort / File(s) Summary
Session & Client logic
packages/clerk-js/src/core/clerk.ts
- setActive: only run transitive state updates when newSession is not pending and either the session id differs from current or an organization switch is requested.
- updateClient: on first client assignment, derive and apply an initial session immediately (via options.selectInitialSession or default); on subsequent client updates when the new client contains sessions, derive/apply a new initial session and emit a TokenUpdate reflecting the new session token.
Tests
packages/clerk-js/src/core/__tests__/clerk.test.ts
- Added tests for setActive during navigation-redirects: verify no transitive update when session id is unchanged; verify transitive update when session id changes.
- Added test ensuring updateClient sets Clerk session after sign-in when touch() triggers updateClient.
Release notes
.changeset/upset-words-fly.md
- Added a changeset entry for a patch release: "Fix session setting immediately after sign in" targeting @clerk/clerk-js.

Sequence Diagram(s)

sequenceDiagram
    participant Cookie as JWT Cookie
    participant PreClient as Preliminary Client
    participant Clerk as ClerkCore
    participant Fetch as Network Fetch
    participant Client as Final Client
    participant State as SessionState

    Note over Cookie,PreClient: derive preliminary client/session if JWT present
    Cookie->>PreClient: derive client/session
    PreClient->>Clerk: updateClient(preliminaryClient)
    Clerk->>State: apply initial session & accessors
    Clerk->>Fetch: request final client (async)
    Fetch->>Client: return full client
    Client->>Clerk: updateClient(finalClient)
    Clerk->>State: reconcile/apply sessions, emit TokenUpdate if needed
Loading
sequenceDiagram
    participant Caller as Caller
    participant Clerk as ClerkCore
    participant State as SessionState

    Note over Caller,Clerk: setActive condensed 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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Inspect setActive branches for pending/session-equality and organization-switch logic.
  • Verify updateClient first-assignment vs subsequent-assignment paths and TokenUpdate emission.
  • Review new tests for correctness and coverage of sign-in/updateClient interaction.

Poem

🐇
I found a cookie, gentle and small,
I built a client and gave it a call.
Sessions settle soft, no frantic spin,
Tokens align and calm creeps in.
Hooray, the state now purrs within.

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main fix: ensuring sessionId is set after sign-in, which aligns perfectly with the PR's core objective and changes.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/null-session-id-after-sign-in

Comment @coderabbitai help to get the list of available commands and usage tips.

@jacekradko jacekradko changed the title fix(clerk-js): ensure sessionId is available immeditately after sign in fix(clerk-js): Ensure sessionId is set after sign in Oct 31, 2025
@jacekradko jacekradko marked this pull request as ready for review October 31, 2025 21:39
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 f47b5a3 and f0d9553.

📒 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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/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 clears

Skipping the transitive reset when we’re navigating with the same or a pending session keeps sessionId stable through the redirect and directly addresses the regression. Well done.


2601-2605: Preloading from the cookie is a solid improvement

Hydrating from the JWT before the /client fetch lands removes the visible gap where sessionId was null on the next page. This sequencing change makes the whole flow feel instant.

}

if (newSession?.status !== 'pending') {
if (newSession?.status !== 'pending' && this.session?.id !== newSession?.id) {
Copy link
Member

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

Copy link
Member Author

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

Copy link
Member Author

Choose a reason for hiding this comment

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

Copy link
Member

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 31, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 51b2f6a

@blacksmith-sh
Copy link

blacksmith-sh bot commented Oct 31, 2025

Found 2 test failures on Blacksmith runners:

Test View Logs
[chrome] › integration/tests/
session-tasks-multi-session.test.ts:33:9 › session tasks multi-session flow @nextjs › l
ong-running--next.appRouter.withSessionTasks › when switching sessions, navigate to tas
k
View Logs
[chrome] › integration/tests/tanstack-start/
basic.test.ts:43:9 › basic tests for TanStack Start @tanstack-react-start › long-runnin
g--tanstack.react-start › can sign in and user button renders
View Logs


Fix in Cursor

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 f0d9553 and 7964a90.

📒 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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/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 updateClient method (line 2353) calls #emit() at line 2393 every time it's invoked. During initialization, this occurs twice in rapid succession:

  1. Line 2604: updateClient(preliminaryClient) from JWT cookie → #emit() notifies listeners
  2. Line 2609: updateClient(res) from FAPI fetch → #emit() notifies listeners

This 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 updateClient to 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 updated lastActiveOrganizationId. The setTransitiveState() 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.

@jacekradko
Copy link
Member Author

!snapshot

@clerk-cookie
Copy link
Collaborator

Hey @jacekradko - the snapshot version command generated the following package versions:

Package Version
@clerk/agent-toolkit 0.1.45-snapshot.v20251103041116
@clerk/astro 2.14.3-snapshot.v20251103041116
@clerk/backend 2.19.2-snapshot.v20251103041116
@clerk/chrome-extension 2.7.11-snapshot.v20251103041116
@clerk/clerk-js 5.103.2-snapshot.v20251103041116
@clerk/elements 0.23.76-snapshot.v20251103041116
@clerk/clerk-expo 2.17.4-snapshot.v20251103041116
@clerk/expo-passkeys 0.4.13-snapshot.v20251103041116
@clerk/express 1.7.44-snapshot.v20251103041116
@clerk/fastify 2.5.1-snapshot.v20251103041116
@clerk/localizations 3.26.5-snapshot.v20251103041116
@clerk/nextjs 6.34.2-snapshot.v20251103041116
@clerk/nuxt 1.11.3-snapshot.v20251103041116
@clerk/clerk-react 5.53.5-snapshot.v20251103041116
@clerk/react-router 2.1.7-snapshot.v20251103041116
@clerk/remix 4.13.10-snapshot.v20251103041116
@clerk/shared 3.30.0-snapshot.v20251103041116
@clerk/tanstack-react-start 0.26.6-snapshot.v20251103041116
@clerk/testing 1.13.10-snapshot.v20251103041116
@clerk/themes 2.4.31-snapshot.v20251103041116
@clerk/types 4.97.0-snapshot.v20251103041116
@clerk/vue 1.14.10-snapshot.v20251103041116

Tip: Use the snippet copy button below to quickly install the required packages.
@clerk/agent-toolkit

npm i @clerk/[email protected] --save-exact

@clerk/astro

npm i @clerk/[email protected] --save-exact

@clerk/backend

npm i @clerk/[email protected] --save-exact

@clerk/chrome-extension

npm i @clerk/[email protected] --save-exact

@clerk/clerk-js

npm i @clerk/[email protected] --save-exact

@clerk/elements

npm i @clerk/[email protected] --save-exact

@clerk/clerk-expo

npm i @clerk/[email protected] --save-exact

@clerk/expo-passkeys

npm i @clerk/[email protected] --save-exact

@clerk/express

npm i @clerk/[email protected] --save-exact

@clerk/fastify

npm i @clerk/[email protected] --save-exact

@clerk/localizations

npm i @clerk/[email protected] --save-exact

@clerk/nextjs

npm i @clerk/[email protected] --save-exact

@clerk/nuxt

npm i @clerk/[email protected] --save-exact

@clerk/clerk-react

npm i @clerk/[email protected] --save-exact

@clerk/react-router

npm i @clerk/[email protected] --save-exact

@clerk/remix

npm i @clerk/[email protected] --save-exact

@clerk/shared

npm i @clerk/[email protected] --save-exact

@clerk/tanstack-react-start

npm i @clerk/[email protected] --save-exact

@clerk/testing

npm i @clerk/[email protected] --save-exact

@clerk/themes

npm i @clerk/[email protected] --save-exact

@clerk/types

npm i @clerk/[email protected] --save-exact

@clerk/vue

npm i @clerk/[email protected] --save-exact

Copy link
Member

@brkalow brkalow left a 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?

Comment on lines 2400 to 2404
} else if (!isFirstClientSet && newClient.sessions?.length > 0) {
const session = this.#options.selectInitialSession
? this.#options.selectInitialSession(newClient)
: this.#defaultSession(newClient);
this.#setAccessors(session);
Copy link
Member

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?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, it is. This handles the case where updateClient() is executed during touch(). In that call we get the piggybacked client data. The key here is that this is an else branch of if (this.session) { which we do not have at this point.

So without this else, we do nothing here and just this.#emit(); an empty session.

Copy link

Choose a reason for hiding this comment

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

Oh! Had to dig through the code and think for a bit to get it, but:

  • First updateClient is guaranteed to set a session
  • But if session is later removed, for example because of transitive state..
  • ..and updateClient is called during that time (touch), we currently don't set the new session?

Very nice find. Adding a comment might be helpful here.

Copy link
Member

Choose a reason for hiding this comment

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

Shouldn't this be covered by updateClient ?

Copy link

Choose a reason for hiding this comment

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

That's what this PR adds. It might be easier to grok looking at it like this:

  updateClient = (newClient: ClientResource): void => {
    const isFirstClientSet = !this.client;

    if (isFirstClientSet) {
      // If first time setting client, also set session
      // Note: This does _not_ trigger during transitive state as we still have a client
    }
    this.client = newClient;

    if (this.session) {
      // Previously we only set a new session if we already had an active session,
      // which we don't during transitive state
    } else if (!isFirstClientSet && newClient.sessions?.length > 0) {
      // Now, if client is set, but not session, and there is a new session to set, set it
    }

    this.#emit();
  };

Copy link
Member Author

Choose a reason for hiding this comment

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

@Ephem that's a pretty good summary. This is my mental model of this mechanism:

updateClient = (newClient: ClientResource): void => {
  const isFirstClientSet = !this.client;

  if (isFirstClientSet) {
    // First time setting client (during initialization)
    // Also set the initial session from the new client
  }

  this.client = newClient;

  if (this.session) {
    // We have an active session - refresh it with updated data from newClient
    // This is the normal path during regular operation
  } else if (!isFirstClientSet && newClient.sessions?.length > 0) {
    // Race condition recovery path:
    // - Client was already set (so NOT first initialization)
    // - Session is currently falsy (e.g., cleared by setTransitiveState during setActive)
    // - BUT newClient has session data (e.g., from touch() response that piggybacked)
    // → Restore the session immediately to prevent null flash
  }

  this.#emit();
};

Copy link

Choose a reason for hiding this comment

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

Thinking about this some more, I realize I still don't understand how the this.session goes from undefined to null because of this? Shouldn't the this.#emit be emitting the existing session, which is undefined? 🤔

Copy link

Choose a reason for hiding this comment

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

I think I found the reason here: #7157 (comment)

(Just crossposting here to keep a good history if someone stumbles across this in the future)

}

if (newSession?.status !== 'pending') {
if (newSession?.status !== 'pending' && (this.session?.id !== newSession?.id || shouldSwitchOrganization)) {
Copy link
Member

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.

Copy link
Member

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 ?

Copy link
Member Author

Choose a reason for hiding this comment

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

This check prevents calling #setTransitiveState() unnecessarily. It ensures we only clear the transitive state (which sets the session to undefined) when the session is changing or the org is changing.

Without it you get unnecessary session → undefined → session when nothing changed

Copy link

Choose a reason for hiding this comment

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

Is this what triggered during the sign-in, causing session to be undefined when the updateClient call ran, causing it to not update the session?

So this PR kind of fixes the sign-in bug from two separate angles?

Copy link
Member Author

Choose a reason for hiding this comment

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

@Ephem Exactly! Without this, every navigation with setActive() would clear the session unnecessarily, opening the window for a race condition where updateClient() would run before setActive() can set and emit the session

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • 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 d29ec53 and fc11bb5.

📒 Files selected for processing (1)
  • packages/clerk-js/src/core/clerk.ts (3 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
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/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 (1)
packages/react/src/isomorphicClerk.ts (1)
  • session (682-688)
⏰ 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 (2)
packages/clerk-js/src/core/clerk.ts (2)

1422-1422: LGTM! Transitive state optimization prevents unnecessary transitions.

The condition correctly ensures transitive state is only triggered when the session is not pending AND (the session ID changes OR an organization switch is requested). This prevents unnecessary session → undefined → session cycles when nothing has changed, while still supporting organization switching as discussed in the past review comments.


2361-2370: LGTM! Clear refactoring with explicit first-client detection.

The introduction of isFirstClientSet makes the intent explicit and improves readability. The logic correctly handles initial session selection when the client is first set.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/clerk-js/src/core/__tests__/clerk.test.ts (1)

2597-2627: Clarify test description.

The test description mentions "when touch() response triggers updateClient" but the test doesn't actually simulate a touch() call—it directly invokes updateClient() twice. While the test correctly verifies the updateClient logic that handles the post-sign-in scenario, consider updating the description for accuracy.

Suggested description:

-    it('sets session after sign-in when touch() response triggers updateClient', () => {
+    it('sets session when updateClient is called with session data after being called with empty client', () => {

Alternatively, to keep the context of the sign-in flow:

-    it('sets session after sign-in when touch() response triggers updateClient', () => {
+    it('sets session when updateClient is called with fresh client data (e.g., after sign-in touch response)', () => {
📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between fc11bb5 and 89fc47e.

📒 Files selected for processing (1)
  • packages/clerk-js/src/core/__tests__/clerk.test.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/__tests__/clerk.test.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/__tests__/clerk.test.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.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/__tests__/clerk.test.ts
**/*.{ts,tsx}

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

Use proper TypeScript error types

**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoid any type - prefer unknown when type is uncertain, then narrow with type guards
Use interface for object shapes that might be extended
Use type for unions, primitives, and computed types
Prefer readonly properties for immutable data structures
Use private for internal implementation details
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Prefer readonly for properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Use const assertions for literal types: as const
Use satisfies operator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports: import type { ... } from ...
No any types without justification
Proper error handling with typed errors
Consistent use of readonly for immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.ts
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/clerk-js/src/core/__tests__/clerk.test.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}

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

Visual regression testing should be performed for UI components.

Files:

  • packages/clerk-js/src/core/__tests__/clerk.test.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/__tests__/clerk.test.ts
**/__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/clerk-js/src/core/__tests__/clerk.test.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/__tests__/clerk.test.ts (1)
packages/clerk-js/src/core/clerk.ts (1)
  • Clerk (197-3015)
⏰ 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/__tests__/clerk.test.ts (2)

236-273: LGTM! Well-structured test for session ID optimization.

The test correctly verifies that setTransitiveState is not called when the active session ID remains unchanged during navigation, preventing unnecessary UI flickers. The listener-based approach to detect transitive state is elegant.


275-320: LGTM! Good complementary test for session switching.

This test properly verifies that setTransitiveState is called when switching between different sessions, ensuring the UI state is cleared before the new session is applied. Works well alongside the previous test to cover both scenarios.

@jacekradko
Copy link
Member Author

!snapshot

@clerk-cookie
Copy link
Collaborator

Hey @jacekradko - the snapshot version command generated the following package versions:

Package Version
@clerk/agent-toolkit 0.1.46-snapshot.v20251104193921
@clerk/astro 2.14.4-snapshot.v20251104193921
@clerk/backend 2.19.3-snapshot.v20251104193921
@clerk/chrome-extension 2.7.12-snapshot.v20251104193921
@clerk/clerk-js 5.103.3-snapshot.v20251104193921
@clerk/elements 0.23.77-snapshot.v20251104193921
@clerk/clerk-expo 2.18.0-snapshot.v20251104193921
@clerk/expo-passkeys 0.4.14-snapshot.v20251104193921
@clerk/express 1.7.45-snapshot.v20251104193921
@clerk/fastify 2.5.2-snapshot.v20251104193921
@clerk/localizations 3.26.6-snapshot.v20251104193921
@clerk/nextjs 6.34.3-snapshot.v20251104193921
@clerk/nuxt 1.11.4-snapshot.v20251104193921
@clerk/clerk-react 5.53.6-snapshot.v20251104193921
@clerk/react-router 2.1.8-snapshot.v20251104193921
@clerk/remix 4.13.11-snapshot.v20251104193921
@clerk/shared 3.30.1-snapshot.v20251104193921
@clerk/tanstack-react-start 0.26.7-snapshot.v20251104193921
@clerk/testing 1.13.11-snapshot.v20251104193921
@clerk/themes 2.4.32-snapshot.v20251104193921
@clerk/types 4.97.1-snapshot.v20251104193921
@clerk/vue 1.14.11-snapshot.v20251104193921

Tip: Use the snippet copy button below to quickly install the required packages.
@clerk/agent-toolkit

npm i @clerk/[email protected] --save-exact

@clerk/astro

npm i @clerk/[email protected] --save-exact

@clerk/backend

npm i @clerk/[email protected] --save-exact

@clerk/chrome-extension

npm i @clerk/[email protected] --save-exact

@clerk/clerk-js

npm i @clerk/[email protected] --save-exact

@clerk/elements

npm i @clerk/[email protected] --save-exact

@clerk/clerk-expo

npm i @clerk/[email protected] --save-exact

@clerk/expo-passkeys

npm i @clerk/[email protected] --save-exact

@clerk/express

npm i @clerk/[email protected] --save-exact

@clerk/fastify

npm i @clerk/[email protected] --save-exact

@clerk/localizations

npm i @clerk/[email protected] --save-exact

@clerk/nextjs

npm i @clerk/[email protected] --save-exact

@clerk/nuxt

npm i @clerk/[email protected] --save-exact

@clerk/clerk-react

npm i @clerk/[email protected] --save-exact

@clerk/react-router

npm i @clerk/[email protected] --save-exact

@clerk/remix

npm i @clerk/[email protected] --save-exact

@clerk/shared

npm i @clerk/[email protected] --save-exact

@clerk/tanstack-react-start

npm i @clerk/[email protected] --save-exact

@clerk/testing

npm i @clerk/[email protected] --save-exact

@clerk/themes

npm i @clerk/[email protected] --save-exact

@clerk/types

npm i @clerk/[email protected] --save-exact

@clerk/vue

npm i @clerk/[email protected] --save-exact

@jacekradko jacekradko marked this pull request as draft November 6, 2025 14:43
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.

7 participants