-
Notifications
You must be signed in to change notification settings - Fork 402
poc(clerk-js): Initialize client more quickly [POC - DO NOT MERGE] #7139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThe 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
packages/clerk-js/src/core/clerk.ts(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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/core/clerk.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/clerk.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/clerk.ts (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)
| const jwtInCookie = this.#authService?.getSessionCookie(); | ||
| if (jwtInCookie) { | ||
| const preliminaryClient = createClientFromJwt(jwtInCookie); | ||
| this.updateClient(preliminaryClient); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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:
- 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);
+ }
}- 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.tsLength 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.tsLength 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.tsLength 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:
- 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);
+ }
}- 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.
|
Found 13 test failures on Blacksmith runners:
|
Description
Speed up initialization of Clerk Client by using JWT from session cookie instead of waiting for the fetch to resolve
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit