Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Oct 31, 2025

Description

Initial attempt to resolve the sessionID being null immediately after signing in and navigating to the next route.

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 resets when the active session is unchanged or pending, reducing interruptions.
    • Faster startup by pre-populating client/session state from existing tokens, shortening boot time.
  • Reliability

    • More resilient initialization on network or fetch failures by using stored tokens to bootstrap state and resume token checks, improving offline/degraded connectivity behavior.

@changeset-bot
Copy link

changeset-bot bot commented Oct 31, 2025

⚠️ No Changeset found

Latest commit: 5112830

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a 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 3, 2025 10:41pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 31, 2025

Walkthrough

setActive 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

Cohort / File(s) Summary
Session & Client logic
packages/clerk-js/src/core/clerk.ts
- setActive: perform transitive state updates only when the new session is not pending and either differs from current active session or an organization switch is requested.
- updateClient: on first client assignment, derive and apply an initial session immediately; on later updates, derive an initial session via options.selectInitialSession or default and apply accessors.
- Initialization/error paths: derive a preliminary client from a JWT cookie and call updateClient(preliminaryClient) to pre-populate client/session state before or when fetch fails.

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

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Inspect setActive conditional branches for pending/session-equality and org-switch logic.
  • Verify updateClient paths: first-time vs subsequent client assignment, initial session derivation, and accessor application.
  • Validate cookie JWT parsing and safe fallback behavior in bootstrap and fetch-failure branches.

Poem

🐇
I sniffed a cookie, found a tiny key,
I stitched a client quick as could be.
No frantic resets, just a calm little hop—
Sessions tap-dance, then softly stop.
Hooray for warm starts beneath clover tree!

Pre-merge checks and finishing touches

✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The PR title "fix(clerk-js): Ensure sessionId is set after sign in" accurately reflects the core objective of the changes. The modifications to setActive, updateClient, and client initialization logic are all designed to address the issue where sessionId is null immediately after sign-in. The title is specific and clear, identifying both the problem (sessionId not being set) and when it occurs (after sign in), allowing a teammate scanning history to quickly understand the PR's purpose without confusion.
✨ 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

📜 Recent 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 7964a90 and 6397235.

📒 Files selected for processing (1)
  • packages/clerk-js/src/core/clerk.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/clerk-js/src/core/clerk.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (22)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Static analysis
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)

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

Comment on lines +2601 to 2609
const jwtInCookie = this.#authService?.getSessionCookie();
if (jwtInCookie) {
const preliminaryClient = createClientFromJwt(jwtInCookie);
this.updateClient(preliminaryClient);
}

return Client.getOrCreateInstance()
.fetch()
.then(res => this.updateClient(res))
Copy link
Member

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

@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: 5112830

@blacksmith-sh
Copy link

blacksmith-sh bot commented Oct 31, 2025

Found 45 test failures on Blacksmith runners:

Test View Logs
[chrome] › integration/tests/astro/
components.test.ts:378:7 › basic flows for @astro › long-running--astro.node.withCustom
Roles › react/ render user profile with streamed data
View Logs
[chrome] › integration/tests/custom-flows/
sign-in.test.ts:51:7 › Custom Flows Sign In @custom › can sign in with email code
View Logs
[chrome] › integration/tests/custom-flows/
sign-in.test.ts:65:7 › Custom Flows Sign In @custom › renders error with invalid email
code
View Logs
[chrome] › integration/tests/custom-flows/
sign-in.test.ts:78:7 › Custom Flows Sign In @custom › can sign in with phone code
View Logs
[chrome] › integration/tests/custom-flows/
sign-in.test.ts:92:7 › Custom Flows Sign In @custom › can sign in with password
View Logs
[chrome] › integration/tests/custom-flows/
sign-up.test.ts:53:7 › Custom Flows Sign Up @custom › can sign up with email and passwo
rd
View Logs
[chrome] › integration/tests/expo-web/
basic.test.ts:35:9 › basic tests for expo web @expo-web › long-running--expo.expo-web ›
can sign in and user button renders
View Logs
[chrome] › integration/tests/expo-web/
custom-flows.test.ts:35:9 › custom flows test suite @expo-web › long-running--expo.expo
-web › sign in using custom flow
View Logs
[chrome] › integration/tests/expo-web/
custom-flows.test.ts:55:9 › custom flows test suite @expo-web › long-running--expo.expo
-web › sign up using custom flow and also delete user
View Logs
[chrome] › integration/tests/express/
basic.test.ts:24:7 › basic tests for @express › long-running--express.vite.withEmailCod
es › authenticates protected routes when user is signed in using getAuth()
View Logs
[chrome] › integration/tests/express/
basic.test.ts:42:7 › basic tests for @express › long-running--express.vite.withEmailCod
es › rejects protected routes when user is not authenticated using getAuth()
View Logs
[chrome] › integration/tests/express/
basic.test.ts:54:7 › basic tests for @express › long-running--express.vite.withEmailCod
es › authenticates protected routes when user is signed in using legacy req.auth approa
ch
View Logs
[chrome] › integration/tests/express/
basic.test.ts:75:7 › basic tests for @express › long-running--express.vite.withEmailCod
es › rejects protected routes when user is not authenticated using legacy req.auth appr
oach
View Logs
[chrome] › integration/tests/handshake/
handshake.test.ts:60:9 › handshake flow @handshake › with Production instance › when th
e client uat cookies are deleted
View Logs
[chrome] › integration/tests/handshake/
handshake.test.ts:60:9 › handshake flow @handshake › with Production instance › when th
e client uat cookies are deleted
View Logs
[chrome] › integration/tests/localhost/
localhost-different-port-different-instance.test.ts:42:7 › multiple apps running on loc
alhost using different Clerk instances @localhost › sessions are independent between th
e different apps
View Logs
[chrome] › integration/tests/localhost/
localhost-different-port-same-instance.test.ts:40:7 › multiple apps running on localhos
t using same Clerk instance @localhost › the cookies are aligned for the root and sub d
omains
View Logs
[chrome] › integration/tests/next-account-portal/
clerk-v4-ap-core-1.test.ts:30:7 › Next with ClerkJS V4 <->
Account Portal Core 1 @ap-flows › sign in
View Logs
[chrome] › integration/tests/next-account-portal/
clerk-v5-ap-core-1.test.ts:30:7 › Next with ClerkJS V5 <->
Account Portal Core 1 @ap-flows › sign in
View Logs
[chrome] › integration/tests/
oauth-flows.test.ts:38:7 › oauth flows @nextjs › long-running--next.appRouter.withEmail
Codes › sign up with custom oauth provider
View Logs
[chrome] › integration/tests/
oauth-flows.test.ts:38:7 › oauth flows @nextjs › long-running--next.appRouter.withEmail
Codes › sign up with custom oauth provider
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:110:9 › pricing table @billing › long-running--withBilling.vue.vi
te › when signed in flow › subscribes to a plan
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:250:7 › pricing table @billing › long-running--withBilling.astro.
node › starts free trial subscription for new user
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:250:7 › pricing table @billing › long-running--withBilling.next.a
ppRouter › starts free trial subscription for new user
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:456:9 › pricing table @billing › long-running--withBilling.vue.vi
te › in UserProfile › renders pricing table, subscribes to a plan, revalidates payment
method on complete and then downgrades to free
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:588:9 › pricing table @billing › long-running--withBilling.next.a
ppRouter › in UserProfile › adds payment method via checkout and resets stripe setup in
tent after failed payment
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:97:9 › pricing table @billing › long-running--withBilling.astro.n
ode › when signed in flow › when signed in, clicking checkout button open checkout draw
er
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:97:9 › pricing table @billing › long-running--withBilling.next.ap
pRouter › when signed in flow › when signed in, clicking checkout button open checkout
drawer
View Logs
[chrome] › integration/tests/
protect.test.ts:103:7 › authorization @nextjs › long-running--next.appRouter.withCustom
Roles › Protect in RSCs and RCCs as viewer
View Logs
[chrome] › integration/tests/
redirects.test.ts:34:9 › redirect props @nextjs › long-running--next.appRouter.withEmai
lCodes › SignInButton › sign in button respects forceRedirectUrl
View Logs
[chrome] › integration/tests/
redirects.test.ts:34:9 › redirect props @nextjs › long-running--next.appRouter.withEmai
lCodes › SignInButton › sign in button respects forceRedirectUrl
View Logs
[chrome] › integration/tests/
reverification.test.ts:217:11 › @nextjs require @reverification › long-running--next.ap
pRouter.withReverification › reverification error from Action
View Logs
[chrome] › integration/tests/
reverification.test.ts:217:11 › @nextjs require @reverification › long-running--next.ap
pRouter.withReverification › reverification error from Action
View Logs
[chrome] › integration/tests/
reverification.test.ts:250:11 › @nextjs require @reverification › long-running--next.ap
pRouter.withReverification › reverification recovery from Action
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/
session-tasks-sign-in.test.ts:36:9 › session tasks after sign-in flow @nextjs › long-ru
nning--next.appRouter.withSessionTasks › with email and password, navigate to task on a
fter sign-in
View Logs
[chrome] › integration/tests/
session-tasks-sign-in.test.ts:36:9 › session tasks after sign-in flow @nextjs › long-ru
nning--next.appRouter.withSessionTasks › with email and password, navigate to task on a
fter sign-in
View Logs
[chrome] › integration/tests/
session-tasks-sign-up.test.ts:54:9 › session tasks after sign-up flow @nextjs › long-ru
nning--next.appRouter.withSessionTasks › navigate to task on after sign-up
View Logs
[chrome] › integration/tests/
session-tasks-sign-up.test.ts:54:9 › session tasks after sign-up flow @nextjs › long-ru
nning--next.appRouter.withSessionTasks › navigate to task on after sign-up
View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:26:7 › sign in flow @generic @nextjs › long-running--next.appRoute
r.withEmailCodes › sign in with email and password
View Logs
[chrome] › integration/tests/
sign-in-flow.test.ts:26:7 › sign in flow @generic @nextjs › long-running--next.appRoute
r.withEmailCodes › sign in with email and password
View Logs
[chrome] › integration/tests/
sign-in-or-up-flow.test.ts:29:9 › sign-in-or-up flow @nextjs › long-running--next.appRo
uter.withSignInOrUpFlow › sign-in › flows are combined
View Logs
[setup] › integration/tests/
global.setup.ts:7:6 › start long running apps ─────────────────────
View Logs
[setup] › integration/tests/
global.setup.ts:7:6 › start long running apps ─────────────────────
View Logs
[setup] › integration/tests/
global.setup.ts:7:6 › start long running apps ─────────────────────
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/agent-toolkit@0.1.45-snapshot.v20251103041116 --save-exact

@clerk/astro

npm i @clerk/astro@2.14.3-snapshot.v20251103041116 --save-exact

@clerk/backend

npm i @clerk/backend@2.19.2-snapshot.v20251103041116 --save-exact

@clerk/chrome-extension

npm i @clerk/chrome-extension@2.7.11-snapshot.v20251103041116 --save-exact

@clerk/clerk-js

npm i @clerk/clerk-js@5.103.2-snapshot.v20251103041116 --save-exact

@clerk/elements

npm i @clerk/elements@0.23.76-snapshot.v20251103041116 --save-exact

@clerk/clerk-expo

npm i @clerk/clerk-expo@2.17.4-snapshot.v20251103041116 --save-exact

@clerk/expo-passkeys

npm i @clerk/expo-passkeys@0.4.13-snapshot.v20251103041116 --save-exact

@clerk/express

npm i @clerk/express@1.7.44-snapshot.v20251103041116 --save-exact

@clerk/fastify

npm i @clerk/fastify@2.5.1-snapshot.v20251103041116 --save-exact

@clerk/localizations

npm i @clerk/localizations@3.26.5-snapshot.v20251103041116 --save-exact

@clerk/nextjs

npm i @clerk/nextjs@6.34.2-snapshot.v20251103041116 --save-exact

@clerk/nuxt

npm i @clerk/nuxt@1.11.3-snapshot.v20251103041116 --save-exact

@clerk/clerk-react

npm i @clerk/clerk-react@5.53.5-snapshot.v20251103041116 --save-exact

@clerk/react-router

npm i @clerk/react-router@2.1.7-snapshot.v20251103041116 --save-exact

@clerk/remix

npm i @clerk/remix@4.13.10-snapshot.v20251103041116 --save-exact

@clerk/shared

npm i @clerk/shared@3.30.0-snapshot.v20251103041116 --save-exact

@clerk/tanstack-react-start

npm i @clerk/tanstack-react-start@0.26.6-snapshot.v20251103041116 --save-exact

@clerk/testing

npm i @clerk/testing@1.13.10-snapshot.v20251103041116 --save-exact

@clerk/themes

npm i @clerk/themes@2.4.31-snapshot.v20251103041116 --save-exact

@clerk/types

npm i @clerk/types@4.97.0-snapshot.v20251103041116 --save-exact

@clerk/vue

npm i @clerk/vue@1.14.10-snapshot.v20251103041116 --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 +2615 to +2619
const jwtInCookie = this.#authService?.getSessionCookie();
if (jwtInCookie) {
const preliminaryClient = createClientFromJwt(jwtInCookie);
this.updateClient(preliminaryClient);
}
Copy link
Member

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.

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?

}

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 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants