Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Nov 4, 2025

Description

Speed up initialization of Clerk Client by using JWT from session cookie instead of waiting for the fetch to resolve

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

  • Bug Fixes
    • Improved session initialization by enabling earlier session state loading during app startup, reducing initial load time for returning users with existing sessions.

@changeset-bot
Copy link

changeset-bot bot commented Nov 4, 2025

⚠️ No Changeset found

Latest commit: 7ec14e8

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 Nov 4, 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 2:38pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 4, 2025

Walkthrough

The Clerk.init flow now includes an early bootstrap mechanism that attempts to load client state from an existing session cookie before the main fetch operation. When a session cookie is present, it creates a preliminary client from the JWT and updates the current client with this preloaded state.

Changes

Cohort / File(s) Change Summary
Early Session Bootstrap
packages/clerk-js/src/core/clerk.ts
Added preliminary client initialization from session cookie before main Client.fetch(). New flow calls getSessionCookie(), parses JWT via createClientFromJwt(), and updates client with updateClient() prior to existing fetch logic.

Sequence Diagram

sequenceDiagram
    actor User
    participant Clerk
    participant AuthService
    participant Client
    participant Server

    User->>Clerk: init()
    
    rect rgb(200, 230, 255)
        Note over Clerk,AuthService: NEW: Early Bootstrap Path
        Clerk->>AuthService: getSessionCookie()
        AuthService-->>Clerk: session JWT (if exists)
        opt Session cookie present
            Clerk->>Clerk: createClientFromJwt(jwtInCookie)
            Clerk->>Client: updateClient(preliminaryClient)
            Client-->>Clerk: preliminary state loaded
        end
    end
    
    rect rgb(220, 220, 220)
        Note over Clerk,Server: Existing Flow: Main Fetch
        Clerk->>Client: getOrCreateInstance().fetch()
        Client->>Server: fetch session data
        Server-->>Client: latest session state
        Client-->>Clerk: fetch complete
    end
    
    Clerk-->>User: initialization complete
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Key areas requiring attention:
    • JWT parsing and validation logic in createClientFromJwt()
    • Error handling if session cookie is malformed or expired
    • Reconciliation behavior when preliminary client differs from fetch result
    • Potential race conditions or state consistency issues between bootstrap and main fetch
    • Impact on initialization error handling and recovery paths

Poem

🐰✨ A cookie arrives with a JWT so sweet,
We parse it with joy—what a bootstrap treat!
Before the fetch dance, the session's alive,
Client state pre-loaded, we're off to a dive! 🍪

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 title accurately describes the main change: initializing the Clerk client more quickly by using an early JWT bootstrap from session cookies, as confirmed by the code changes.
✨ 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 feat/initialize-client-more-quickly

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 4, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: 7ec14e8

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 61422b2 and 7ec14e8.

📒 Files selected for processing (1)
  • packages/clerk-js/src/core/clerk.ts (1 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/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). (16)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Static analysis
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)

Comment on lines +2608 to +2612
const jwtInCookie = this.#authService?.getSessionCookie();
if (jwtInCookie) {
const preliminaryClient = createClientFromJwt(jwtInCookie);
this.updateClient(preliminaryClient);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Double client update may cause unnecessary re-renders and state churn.

Calling updateClient at line 2611 with the preliminary client and again at line 2616 with the fetched client will trigger #emit() twice in rapid succession. Each emission notifies all registered listeners, potentially causing double React re-renders and state updates.

Additionally, this new bootstrap path lacks error handling and debug logging, making it difficult to diagnose issues in production.

Consider these improvements:

  1. Suppress emission for preliminary update to avoid double notifications:
 const jwtInCookie = this.#authService?.getSessionCookie();
 if (jwtInCookie) {
   const preliminaryClient = createClientFromJwt(jwtInCookie);
-  this.updateClient(preliminaryClient);
+  // Set client without emitting to avoid double render
+  this.client = preliminaryClient;
+  if (!this.session) {
+    const session = this.#options.selectInitialSession
+      ? this.#options.selectInitialSession(preliminaryClient)
+      : this.#defaultSession(preliminaryClient);
+    this.#setAccessors(session);
+  }
 }
  1. Add error handling and debug logging:
+try {
   const jwtInCookie = this.#authService?.getSessionCookie();
   if (jwtInCookie) {
+    debugLogger.info('Bootstrapping client from session cookie JWT', {}, 'clerk');
     const preliminaryClient = createClientFromJwt(jwtInCookie);
     this.client = preliminaryClient;
     // ... set accessors
   }
+} catch (err) {
+  debugLogger.warn('Failed to bootstrap client from JWT', { error: err }, 'clerk');
+  // Continue with normal fetch flow
+}

Run the following script to verify how often updateClient triggers listener callbacks in the codebase:


🏁 Script executed:

#!/bin/bash
# Search for listener registrations and updateClient calls to assess impact
echo "=== Listener registrations via addListener ==="
rg -n -C2 '\.addListener\(' --type=ts

echo -e "\n=== updateClient call sites ==="
rg -n -C2 'this\.updateClient\(' packages/clerk-js/src/core/clerk.ts

Length of output: 7186



🏁 Script executed:

#!/bin/bash
# Examine updateClient method implementation and #emit() logic
echo "=== updateClient method implementation (lines 2360-2401) ==="
sed -n '2360,2401p' packages/clerk-js/src/core/clerk.ts

echo -e "\n=== Search for #emit() calls within updateClient ==="
sed -n '2360,2401p' packages/clerk-js/src/core/clerk.ts | grep -n "emit"

echo -e "\n=== #emit() method implementation (around lines 2832-2843) ==="
sed -n '2830,2850p' packages/clerk-js/src/core/clerk.ts

echo -e "\n=== Full context of lines 2608-2625 to see both updateClient calls ==="
sed -n '2608,2625p' packages/clerk-js/src/core/clerk.ts

Length of output: 3001


🏁 Script executed:

#!/bin/bash
# Examine updateClient method implementation and #emit() logic
echo "=== updateClient method implementation (lines 2360-2401) ==="
sed -n '2360,2401p' packages/clerk-js/src/core/clerk.ts

echo -e "\n=== Search for #emit() calls within updateClient ==="
sed -n '2360,2401p' packages/clerk-js/src/core/clerk.ts | grep -n "emit"

echo -e "\n=== #emit() method implementation (around lines 2832-2843) ==="
sed -n '2830,2850p' packages/clerk-js/src/core/clerk.ts

echo -e "\n=== Full context of lines 2608-2625 to see both updateClient calls ==="
sed -n '2608,2625p' packages/clerk-js/src/core/clerk.ts

Length of output: 3001


Double client update will trigger unnecessary listener notifications; add preliminary client without emission.

Confirmed: updateClient() always calls this.#emit() (line 2401), which notifies all registered listeners. The code at lines 2611 and 2616 will trigger this twice in sequence, causing React and other framework listeners to update state twice unnecessarily.

Additionally, the new bootstrap path lacks error handling and debug logging, making it difficult to diagnose issues in production.

Suggested improvements:

  1. Suppress emission for preliminary update to avoid double notifications:
 const jwtInCookie = this.#authService?.getSessionCookie();
 if (jwtInCookie) {
   const preliminaryClient = createClientFromJwt(jwtInCookie);
-  this.updateClient(preliminaryClient);
+  // Set client directly without emitting to avoid duplicate listener notifications
+  this.client = preliminaryClient;
+  if (!this.client) {
+    const session = this.#options.selectInitialSession
+      ? this.#options.selectInitialSession(preliminaryClient)
+      : this.#defaultSession(preliminaryClient);
+    this.#setAccessors(session);
+  }
 }
  1. Add error handling and debug logging:
+try {
   const jwtInCookie = this.#authService?.getSessionCookie();
   if (jwtInCookie) {
+    debugLogger.info('Bootstrapping preliminary client from session cookie', {}, 'clerk');
     const preliminaryClient = createClientFromJwt(jwtInCookie);
     this.client = preliminaryClient;
     // ... set accessors
   }
+} catch (err) {
+  debugLogger.warn('Failed to bootstrap preliminary client from JWT', { error: err }, 'clerk');
+  // Continue with normal fetch flow
+}

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/clerk-js/src/core/clerk.ts around lines 2608 to 2612, the current
bootstrap path calls updateClient() twice which always emits listeners and
causes duplicate notifications; change the first/preliminary client assignment
to set the internal client state without calling this.#emit (e.g. a private
setter or a flag to suppress emission) so only the final successful update
triggers listeners, and wrap the bootstrap client creation path in a try/catch
that logs debug information and errors (use existing logging utility or
this.#logger.debug/error) before falling back so failures are observable and do
not crash silently.

@blacksmith-sh
Copy link

blacksmith-sh bot commented Nov 4, 2025

Found 13 test failures on Blacksmith runners:

Test 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/
pricing-table.test.ts:163:9 › pricing table @billing › long-running--withBilling.astro.
node › when signed in flow › can downgrade to previous plan
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:163:9 › pricing table @billing › long-running--withBilling.next.a
ppRouter › when signed in flow › can downgrade to previous plan
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:163:9 › pricing table @billing › long-running--withBilling.vue.vi
te › when signed in flow › can downgrade to previous plan
View Logs
[chrome] › integration/tests/
pricing-table.test.ts:558:9 › pricing table @billing › long-running--withBilling.next.a
ppRouter › in UserProfile › checkout always revalidates on open
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/
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/
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/
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/
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


Fix in Cursor

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.

3 participants