Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Nov 24, 2025

Description

Split the functionality change from the removal of channel variant here: #7288

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
    • Optimized session token sharing across multiple browser tabs to improve performance when the application is open in more than one tab.

✏️ Tip: You can customize this high-level summary in your review settings.

@changeset-bot
Copy link

changeset-bot bot commented Nov 24, 2025

🦋 Changeset detected

Latest commit: b352cae

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 Minor
@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 Nov 24, 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 24, 2025 9:04pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 24, 2025

Walkthrough

The changes optimize session token sharing across browser tabs by removing build-variant gating and enabling BroadcastChannel support whenever the environment provides it. The token cache now detects and initializes BroadcastChannel listeners conditionally, and integration tests are updated accordingly.

Changes

Cohort / File(s) Change Summary
Documentation
\.changeset/curly-dingos-pay\.md
New changeset documenting a minor version bump for @clerk/clerk-js with notes on session token poller optimization for cross-tab sharing
Integration Tests
integration/tests/session-token-cache/single-session\.test\.ts
Test harness environment altered from BroadcastChannel-based multi-tab sharing to email code-based authentication flow, changing cross-tab token propagation expectations
Core Token Cache
packages/clerk-js/src/core/tokenCache\.ts
Removed channel-build conditional gating; BroadcastChannel listener now initializes whenever BroadcastChannel is available in the environment with environment-detection instead of build variant

Sequence Diagram

sequenceDiagram
    participant Tab1 as Browser Tab 1
    participant BC as BroadcastChannel
    participant Tab2 as Browser Tab 2

    rect rgb(220, 240, 255)
    Note over Tab1,Tab2: Session Token Obtained
    Tab1->>BC: Broadcast: token_refreshed (new_token)
    end

    rect rgb(240, 255, 240)
    Note over Tab1,Tab2: Cross-Tab Sharing (Environment-Detected)
    BC->>Tab2: Deliver: token_refreshed (new_token)
    Tab2->>Tab2: Update local token cache
    end

    rect rgb(255, 250, 240)
    Note over Tab1,Tab2: Subsequent Requests
    Tab2->>Tab2: Use cached token
    Tab1->>Tab1: Use cached token
    end
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~15 minutes

  • Integration test logic change: Verify the email code-based authentication flow is correctly implemented and testing the intended cross-tab scenario
  • Token cache conditional initialization: Confirm BroadcastChannel detection and listener attachment logic handles edge cases (undefined, unavailable, or throwing scenarios)

Poem

🐰 Tabs whisper softly through the channel's stream,
No build gates needed—just environment's dream,
Tokens dance freely from pane to pane,
BroadcastChannel shares the sweet refrain!

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'feat(clerk-js): Add enhanced poller to main browser build' accurately describes the main change: enabling BroadcastChannel-based session token polling in the default browser build by removing channel-variant gating.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ 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/enhanced-poller-browser-build

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Nov 24, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: b352cae

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/tokenCache.ts (1)

210-210: Consider adding explicit return type for clarity.

While the implementation is correct, the async function handleBroadcastMessage would benefit from an explicit Promise<void> return type for better documentation and type safety, especially since the coding guidelines emphasize explicit return types.

Apply this diff:

-  const handleBroadcastMessage = async ({ data }: MessageEvent<SessionTokenEvent>) => {
+  const handleBroadcastMessage = async ({ data }: MessageEvent<SessionTokenEvent>): Promise<void> => {
📜 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 1f9bf68 and c720c5c.

📒 Files selected for processing (3)
  • .changeset/curly-dingos-pay.md (1 hunks)
  • integration/tests/session-token-cache/single-session.test.ts (1 hunks)
  • packages/clerk-js/src/core/tokenCache.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{js,jsx,ts,tsx}

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

All code must pass ESLint checks with the project's configuration

Files:

  • integration/tests/session-token-cache/single-session.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • integration/tests/session-token-cache/single-session.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
**/*.{ts,tsx,js,jsx}

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

Follow established naming conventions (PascalCase for components, camelCase for variables)

Prefer importing types from @clerk/shared/types instead of the deprecated @clerk/types alias

Files:

  • integration/tests/session-token-cache/single-session.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

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

**/*.{test,spec}.{ts,tsx,js,jsx}: Unit tests are required for all new functionality
Verify proper error handling and edge cases
Include tests for all new features

Files:

  • integration/tests/session-token-cache/single-session.test.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • integration/tests/session-token-cache/single-session.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}

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

Use real Clerk instances for integration tests

Files:

  • integration/tests/session-token-cache/single-session.test.ts
**/*.{ts,tsx}

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

**/*.{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
Implement type guards for unknown types using the pattern function isType(value: unknown): value is Type
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 in classes
Use protected for inheritance hierarchies
Use public explicitly for clarity in public APIs
Use mixins for shared behavior across unrelated classes in TypeScript
Use generic constraints with bounded type parameters like <T extends { id: string }>
Use utility types like Omit, Partial, and Pick for data transformation instead of manual type construction
Use discriminated unions instead of boolean flags for state management and API responses
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation at the type level
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Document functions with JSDoc comments including @param, @returns, @throws, and @example tags
Create custom error classes that extend Error for specific error types
Use the Result pattern for error handling instead of throwing exceptions
Use optional chaining (?.) and nullish coalescing (??) operators for safe property access
Let TypeScript infer obvious types to reduce verbosity
Use const assertions with as const for literal types
Use satisfies operator for type checking without widening types
Declare readonly arrays and objects for immutable data structures
Use spread operator and array spread for immutable updates instead of mutations
Use lazy loading for large types...

Files:

  • integration/tests/session-token-cache/single-session.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/tokenCache.ts
packages/**/src/**/*.{ts,tsx,js,jsx}

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

packages/**/src/**/*.{ts,tsx,js,jsx}: Maintain comprehensive JSDoc comments for public APIs
Use tree-shaking friendly exports
Validate all inputs and sanitize outputs
All public APIs must be documented with JSDoc
Use dynamic imports for optional features
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
Implement proper logging with different levels

Files:

  • packages/clerk-js/src/core/tokenCache.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). (34)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 15, RQ)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 14)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (expo-web, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (elements, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Static analysis
  • GitHub Check: Publish with pkg-pr-new
  • GitHub Check: Unit Tests (22, **)
  • GitHub Check: Unit Tests (22, shared, clerk-js, RQ)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
.changeset/curly-dingos-pay.md (1)

1-6: LGTM!

The changeset correctly documents a minor version bump for the cross-tab token sharing optimization. The format follows the standard changeset convention.

integration/tests/session-token-cache/single-session.test.ts (2)

14-14: LGTM!

The test environment configuration correctly enables email code authentication for the test setup, which is used in the sign-in flow below.


49-130: LGTM!

The test correctly validates BroadcastChannel cross-tab token sharing:

  • Tab1 forces a network fetch with skipCache: true and broadcasts the token
  • Tab2 retrieves the broadcasted token from cache without a network request
  • Verification confirms identical tokens and only one network request, proving the optimization works

The 2-second wait on line 108 provides an appropriate buffer for broadcast propagation.

packages/clerk-js/src/core/tokenCache.ts (3)

141-141: LGTM!

The updated comment accurately reflects that BroadcastChannel support is now detected at runtime based on environment capabilities rather than build configuration.


149-164: LGTM!

The runtime detection logic correctly:

  • Checks for BroadcastChannel availability using typeof BroadcastChannel === 'undefined'
  • Returns null when unavailable, allowing graceful degradation
  • Initializes the channel and event listener only once when available
  • Properly handles the async handleBroadcastMessage with explicit void

166-166: LGTM!

Early initialization of the BroadcastChannel ensures the event listener is registered as soon as the cache is created, allowing the tab to receive token broadcasts from other tabs immediately.

@jacekradko jacekradko merged commit 0e521cb into main Nov 24, 2025
43 of 44 checks passed
@jacekradko jacekradko deleted the feat/enhanced-poller-browser-build branch November 24, 2025 21:11
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.

4 participants