Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Oct 30, 2025

Description

Small optimization to only cache a token in SessionTokenCache when it's not already there. This prevents the session token to get broadcast needlessly.

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

  • Tests

    • Added tests verifying token caching, session reconstruction, deduplication of concurrent token requests, and reliable token broadcast behavior.
  • Bug Fixes

    • Prevented duplicate cache entries and unnecessary token fetches during session recovery.
    • Ensured token broadcasts occur consistently when cache entries are created or reset.
  • Chores

    • Added a changeset entry for a patch release describing the caching optimization.

@changeset-bot
Copy link

changeset-bot bot commented Oct 30, 2025

🦋 Changeset detected

Latest commit: bed5cdf

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 30, 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 Oct 30, 2025 8:00pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 30, 2025

Walkthrough

Session token caching logic was tightened: hydrateCache returns early on null, computes tokenId once, and only writes the cache when an entry is absent. Tests were added/updated to verify cache deduplication and that SessionTokenCache.set always broadcasts via postMessage.

Changes

Cohort / File(s) Summary
Token Cache Broadcasting
packages/clerk-js/src/core/__tests__/tokenCache.test.ts
Adds a test asserting SessionTokenCache.set always broadcasts via postMessage, even when a token was already present in the cache.
Session Caching Optimization
packages/clerk-js/src/core/resources/Session.ts
hydrateCache now returns early for null tokens, computes tokenId once into a local variable, checks the cache for an existing entry, and only calls cache set when no entry exists (using the resolved tokenPromise and local tokenId).
Session Resource Tests
packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Removes as any casts from test setup and adds/extends tests to verify that reconstructing a Session with the same last_active_token does not duplicate cache entries or trigger API requests, and that degraded-mode cookie recovery caches tokens appropriately.
Changeset
.changeset/modern-cars-fall.md
Adds a patch changeset documenting the optimization to Session.#hydrateCache to avoid unnecessary caching operations.

Sequence Diagram(s)

sequenceDiagram
    participant Session
    participant TokenCache as SessionTokenCache
    participant Broadcaster as postMessage

    rect rgb(230, 245, 255)
    Session->>Session: hydrateCache(token)
    alt token is null
        Session-->>Session: return (no cache ops)
    else token present
        Session->>Session: compute tokenId (local)
        Session->>TokenCache: get(tokenId)
        alt cache entry exists
            TokenCache-->>Session: entry found
            Session-->>TokenCache: (skip set)
        else no cache entry
            Session->>TokenCache: set(tokenId, { tokenPromise })
            TokenCache-->>Session: set resolved
        end
    end
    end
Loading
sequenceDiagram
    participant Caller
    participant TokenCache as SessionTokenCache
    participant Broadcaster as postMessage

    Caller->>TokenCache: set(tokenId, payload)
    TokenCache->>Broadcaster: postMessage({ tokenId })   %% broadcast always expected by test
    Broadcaster-->>Caller: acknowledged
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Inspect packages/clerk-js/src/core/resources/Session.ts for correct null handling, single tokenId computation, and conditional cache writes.
  • Verify packages/clerk-js/src/core/__tests__/tokenCache.test.ts ensures postMessage is invoked on every set.
  • Review packages/clerk-js/src/core/resources/__tests__/Session.test.ts for new cases preventing duplicate caching and redundant API calls.

Poem

🐰
I hop through code with whiskers bright,
One ID found, I set it right.
If cached or new, I still call out —
A cheerful thump, a broadcast shout! 🥕

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The pull request title "feat(clerk-js): Update SessionTokenCache only if un-cached" clearly and specifically summarizes the main change in the PR. The title directly corresponds to the core optimization implemented in Session.ts, where the hydrateCache method now only updates the cache when there is no existing cached entry, preventing unnecessary broadcasts. The title is concise, specific, and accurately reflects what a reviewer would understand as the primary objective of this changeset. The changeset entry confirms this optimization purpose, validating that the title is fully aligned with the actual changes made.
✨ 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/remove-hydrate-cache

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

@jacekradko jacekradko changed the title feat: remove hydrateCache feat: Update SessionTokenCache only if token is un-cached Oct 30, 2025
@jacekradko jacekradko marked this pull request as ready for review October 30, 2025 19:14
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__/tokenCache.test.ts (1)

281-314: Consider verifying cache state in addition to broadcast behavior.

The test correctly verifies that postMessage is called on each set operation. However, it doesn't verify whether the cache entry itself is updated on the second call. Given the PR objective is about updating the cache only when un-cached, it would strengthen this test to also assert the cache state.

Consider adding cache state verification:

  SessionTokenCache.set({ tokenId, tokenResolver });
  await Promise.resolve();

  expect(mockBroadcastChannel.postMessage).toHaveBeenCalledTimes(1);
  const firstCall = mockBroadcastChannel.postMessage.mock.calls[0][0];
  expect(firstCall.tokenId).toBe(tokenId);
+ expect(SessionTokenCache.size()).toBe(1);
+ const firstCacheEntry = SessionTokenCache.get({ tokenId });

  mockBroadcastChannel.postMessage.mockClear();

  const tokenResolver2 = Promise.resolve(
    new Token({
      id: tokenId,
      jwt: mockJwt,
      object: 'token',
    }) as TokenResource,
  );

  SessionTokenCache.set({ tokenId, tokenResolver: tokenResolver2 });
  await Promise.resolve();

  expect(mockBroadcastChannel.postMessage).toHaveBeenCalledTimes(1);
+ expect(SessionTokenCache.size()).toBe(1);
+ const secondCacheEntry = SessionTokenCache.get({ tokenId });
+ // Verify whether cache entry was replaced or kept (depending on expected behavior)
📜 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 3e0ef92 and 627d872.

📒 Files selected for processing (3)
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1 hunks)
  • packages/clerk-js/src/core/resources/Session.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts (12 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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
packages/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
🧬 Code graph analysis (3)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (2)
packages/clerk-js/src/test/core-fixtures.ts (1)
  • clerkMock (249-256)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (407-407)
packages/clerk-js/src/core/resources/Session.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (407-407)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (407-407)
⏰ 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). (2)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/src/core/resources/Session.ts (1)

133-146: LGTM! Clean implementation of conditional caching.

The changes correctly implement the PR objective:

  1. Early return for null tokens avoids unnecessary operations
  2. Computing tokenId once ensures consistency between the get and set operations
  3. The guard clause prevents duplicate cache entries when Session objects are reconstructed with the same token

This optimization eliminates redundant cache operations while maintaining correct behavior.

packages/clerk-js/src/core/resources/__tests__/Session.test.ts (3)

38-38: Good type safety improvement.

Removing the as any type assertion improves compile-time type checking without affecting runtime behavior.

Also applies to: 79-79, 104-106, 149-149, 177-177, 212-212, 233-233, 252-252, 314-314, 335-335, 360-360, 387-387, 409-409, 436-436


103-146: Excellent test coverage for the cache deduplication behavior.

This test comprehensively verifies that reconstructing a Session with the same token doesn't duplicate cache entries or trigger unnecessary API requests. The assertions properly validate:

  • Cache size remains 1 after reconstruction
  • Same token is returned from both session instances
  • No API calls are made

148-172: Good coverage for degraded mode recovery.

This test ensures that tokens from cookies are properly cached during degraded mode recovery, preventing unnecessary API calls when the token is already available.

@pkg-pr-new
Copy link

pkg-pr-new bot commented Oct 30, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/elements

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

@clerk/clerk-expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/clerk-react

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

@clerk/react-router

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

@clerk/remix

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/themes

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

@clerk/types

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

@clerk/upgrade

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

@clerk/vue

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

commit: bed5cdf

@jacekradko jacekradko changed the title feat: Update SessionTokenCache only if token is un-cached feat(clerk-js): Update SessionTokenCache only if un-cached Oct 30, 2025
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/resources/__tests__/Session.test.ts (1)

38-38: Good refactor: Improved type safety.

Removing the as any casts from clerkMock() improves type safety by relying on the proper typing from the fixture. This makes the tests more maintainable and helps catch type errors at compile time.

Also applies to: 79-79, 177-177, 212-212, 233-233, 252-252, 314-314, 335-335, 360-360, 387-387, 409-409, 436-436

📜 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 555ab90 and bed5cdf.

📒 Files selected for processing (2)
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts (12 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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.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__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
🧬 Code graph analysis (2)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (407-407)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (3)
packages/clerk-js/src/test/core-fixtures.ts (1)
  • clerkMock (249-256)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (407-407)
packages/clerk-js/src/core/resources/Session.ts (1)
  • Session (44-433)
🪛 Gitleaks (8.28.0)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts

[high] 284-284: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ 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 (3)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1)

281-314: LGTM! Test correctly validates cache broadcast behavior.

This test properly verifies that SessionTokenCache.set always broadcasts via postMessage, regardless of whether a token with the same tokenId is already cached. This behavior is essential for multi-tab synchronization, while the optimization (avoiding unnecessary set calls) is handled at the Session class level via the updated hydrateCache method.

Note on static analysis hint:
The Gitleaks warning for line 284 is a false positive. The value 'sess_2GbDB4enNdCa5vS1zpC3Xzg9tK9' is a mock session ID for testing purposes, not a real API key.

packages/clerk-js/src/core/resources/__tests__/Session.test.ts (2)

103-146: Excellent test coverage for cache deduplication.

This test validates the core optimization introduced in this PR: when a Session is reconstructed with the same token, hydrateCache checks for an existing cache entry and avoids redundant cache operations. The assertions correctly verify:

  • Single cache entry after multiple Session constructions
  • Token retrieval works without triggering API requests
  • Cache sharing between session instances

148-172: Good coverage for degraded mode recovery scenario.

This test validates an important edge case where tokens from cookies during degraded mode recovery are properly cached on Session construction. The test correctly verifies that the cached token can be retrieved without triggering API requests, which is essential for resilient operation during network issues.

@jacekradko jacekradko merged commit f47b5a3 into main Oct 31, 2025
42 checks passed
@jacekradko jacekradko deleted the feat/remove-hydrate-cache branch October 31, 2025 04:01
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.

4 participants