Skip to content

Conversation

@jacekradko
Copy link
Member

@jacekradko jacekradko commented Nov 26, 2025

Description

Return a cached token and schedule background refresh if the token is read while in the expiration leeway timeframe.

Fixes: USER-4087

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

Release Notes

  • New Features

    • Added refreshIfStale option to token retrieval API, enabling proactive fresh token fetching when cached token is within refresh leeway.
    • Implemented stale-while-revalidate behavior: immediately returns cached token while automatically refreshing in the background.
  • Improvements

    • Enhanced token expiration handling with improved leeway calculations for more reliable token freshness guarantees.

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

@changeset-bot
Copy link

changeset-bot bot commented Nov 26, 2025

⚠️ No Changeset found

Latest commit: b1104ce

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 26, 2025

Walkthrough

The pull request introduces stale-while-revalidate (SWR) semantics to the token caching system. Instead of immediately evicting stale tokens, the cache now returns them with a needsRefresh flag, enabling immediate token availability while triggering background refresh. This prevents artificial latency when tokens are accessed in hot paths.

Changes

Cohort / File(s) Summary
Token cache core logic
packages/clerk-js/src/core/tokenCache.ts
Modified get() to return TokenCacheGetResult object with entry and needsRefresh flag. Implements SWR by returning stale tokens with refresh signals instead of evicting them. Added resolvedToken field to cache entries for synchronous reads and imported POLLER_INTERVAL_IN_MS for TTL alignment.
Session token retrieval
packages/clerk-js/src/core/resources/Session.ts
Added refreshIfStale option to token retrieval and refactored token fetching into private methods: #fetchToken, #createTokenResolver, and #dispatchTokenEvents. Updated to handle new cache result shape and resolve tokens from either pre-resolved values or token resolvers.
Token type definitions
packages/shared/src/types/session.ts
Added refreshIfStale?: boolean option to GetTokenOptions and reordered fields for consistency.
Session cookie polling
packages/clerk-js/src/core/auth/SessionCookiePoller.ts
Exported new constant POLLER_INTERVAL_IN_MS (5 seconds) and updated internal polling timer to use it.
Cookie service
packages/clerk-js/src/core/auth/AuthCookieService.ts
Updated to use getToken({ refreshIfStale: true }) for proactive token refresh when updating cookies.
Test suite
packages/clerk-js/src/core/__tests__/tokenCache.test.ts, packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Updated all cache lookup assertions to access result?.entry and result?.needsRefresh. Added extensive new test cases verifying SWR behavior, leeway handling, token resolution timing, and multi-session isolation with the new cache API shape.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Session
    participant TokenCache
    participant Poller
    participant Backend

    Client->>Session: getToken({ refreshIfStale: true })
    activate Session
    Session->>TokenCache: get(cacheKey)
    activate TokenCache
    alt Token exists and valid
        TokenCache->>TokenCache: Check remaining TTL vs leeway
        alt Within leeway threshold
            TokenCache-->>Session: { entry, needsRefresh: true }
        else Valid with buffer
            TokenCache-->>Session: { entry, needsRefresh: false }
        end
    else Token stale or missing
        TokenCache-->>Session: undefined
    end
    deactivate TokenCache
    
    alt Token returned with needsRefresh=true
        Session->>Session: Return cached token immediately
        Session-->>Client: token
        par Background Refresh
            Session->>Backend: Fetch fresh token
            Backend-->>Session: New token
            Session->>TokenCache: Update cache with fresh token
            Session->>Poller: Signal refresh complete
        end
    else No token or refreshIfStale=false
        Session->>Backend: Fetch fresh token
        Backend-->>Session: New token
        Session->>TokenCache: Cache new token + resolver
        Session-->>Client: token
    end
    deactivate Session
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Token cache API change: The get() method's return type signature change from TokenCacheEntry | undefined to TokenCacheGetResult | undefined requires verification across all call sites and test assertions.
  • SWR state machine logic: The leeway and TTL calculations in tokenCache.ts (including needsRefresh determination based on remaining TTL, poller interval alignment, and edge cases) warrant careful review.
  • Session token refactoring: The introduction of private methods #fetchToken, #createTokenResolver, and #dispatchTokenEvents consolidates token fetching; verify event dispatch order and resolver lifecycle.
  • Multi-path token resolution: Ensure token resolution from pre-resolved values vs. awaiting resolvers is handled consistently across all code paths.
  • Test coverage density: Substantial test additions for SWR scenarios, leeway variations, and concurrent requests; verify test assumptions align with intended behavior.

Poem

🐰 Hops of joy with tokens swift,
No more waiting—here's the gift!
Stale but spry, we fetch anew,
While background gnomes refresh for you!

Pre-merge checks and finishing touches

✅ Passed checks (5 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): Stale-while-revalidate session token' accurately describes the main feature being implemented - adding stale-while-revalidate behavior for session tokens.
Linked Issues check ✅ Passed All objectives from USER-4087 are met: cache entries are no longer deleted during leeway [tokenCache.ts], cached tokens are returned even within leeway [Session.ts], background refresh is performed asynchronously [SessionCookiePoller.ts, Session.ts], and latency is eliminated by immediate token return.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing stale-while-revalidate behavior: core cache logic [tokenCache.ts], session token handling [Session.ts], cookie polling [SessionCookiePoller.ts], cookie service updates [AuthCookieService.ts], type definitions [session.ts], and comprehensive test coverage aligning with the feature.
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/stale-while-revalidate-token

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

@vercel
Copy link

vercel bot commented Nov 26, 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 Dec 8, 2025 11:20pm

@jacekradko jacekradko marked this pull request as ready for review December 1, 2025 17:23
const tokenResolver = Token.create(path, params, false);

// Cache the promise immediately to prevent concurrent calls from triggering duplicate requests
SessionTokenCache.set({ tokenId, tokenResolver });
Copy link

Choose a reason for hiding this comment

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

This will update the tokenResolver during the background refresh. As per the separate comment, this is not a problem during this getToken call, but wont this be a problem for any subsequent getToken calls?

I haven't verified this, so it's just my reading of the code, but I saw no test cases for this which might also be nice to add.

Say I have two queries using getToken, both triggered from components that render together. The first getToken call triggers a background refresh, which sets the tokenResolver to a promise. This first getToken returns the value immediately as it awaits the previous tokenResolver.

The second call to getToken runs immediately after, does not call a background refresh since one is in progress, but it does read the value via await tokenResolver which is now the promise for the background refresh, because of this, the second getToken call does not SWR correctly even if it should?

Since we might have to touch tokenResolver etc to fix this, this might (or might not!) be a good time to tackle something related too. Awaiting already finished promises still always resolve in a microtask at the end of the JS frame, which is inefficient, so we'll want some way to read the value synchronously after the fetch has finished. Just mentioning that in case this happens to align nicely with a fix for the above.

Copy link
Member Author

Choose a reason for hiding this comment

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

Great catch. Indeed, concurrent calls while refreshing would behave incorrectly as we were awaiting the new in-flight token resolver instead of returning the stale value. To address this, we no longer cache the tokenResolver running in the background until it succeeds, unlike the normal fetch case where it's cached immediately to dedupe requests. We also added a resolvedToken value to the cache so it can be read synchronously without awaiting the resolver, which avoids the microtask overhead you mentioned.

b3f14aa

Copy link
Member Author

Choose a reason for hiding this comment

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

Also expanded the test coverage of the SWR behavior

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 2, 2025

Open in StackBlitz

@clerk/agent-toolkit

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

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/dev-cli

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

@clerk/expo

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

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/localizations

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

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

npm i https://pkg.pr.new/@clerk/ui@7317

@clerk/upgrade

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

@clerk/vue

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

commit: b1104ce

Copy link

@Ephem Ephem left a comment

Choose a reason for hiding this comment

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

I like the latest changes! Using the poller for the background revalidation makes sense to me. I think there's still some torny parts to untangle, and besides the latest comments, something still feels harder than it should be here, so I wonder if we've found the correct mental model for this yet?

I have a few early thoughts, let's chat!


if (expiresSoon) {
// Token expired or dangerously close to expiration - force synchronous refresh
if (remainingTtl <= POLLER_INTERVAL_IN_MS / 1000) {
Copy link

Choose a reason for hiding this comment

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

Default LEEWAY was 10s, and SYNC_LEEWAY was 5s, so if I'm reading this correctly, we used to sync fetch when less than 15s was remaining? Now this value is 5s?

I wonder if 5s is enough considering latency and all other factors?

However we change this it's a breaking change so let's remember to document it properly in the changelog when we've figured it out.

Copy link
Member Author

Choose a reason for hiding this comment

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

Right. Before we would do a blocking fetch under the 15s, now we use the stale value when it's under 15s but more than 5 seconds. The idea there is that the poller would async fetch the token before we get to the 5s. If that doesn't occur then we would force a sync fetch.

Copy link
Member Author

Choose a reason for hiding this comment

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

And yes, this is a breaking change so it's going to be part of Core 3

}

return value.entry;
const effectiveLeeway = Math.max(leeway, MIN_REMAINING_TTL_IN_SECONDS);
Copy link

Choose a reason for hiding this comment

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

This part is a bit weird. MIN_REMAINING_TTL_IN_SECONDS is 15s, and default LEEWAY is 10s, but the Math.max ensures we never go below 15s right?

If this is what we want(?), I think we should increase the LEEWAY to 15s as well, that way we document that "you can only raise this".

Thinking more on it, this PR now changes the public leewayInSeconds to only apply if you also use the internal refreshTokenOnFocus option? That seems off.

try {
const token = await this.clerk.session.getToken();
// Use refreshIfStale to fetch fresh token when cached token is within leeway period
const token = await this.clerk.session.getToken({ refreshIfStale: true });
Copy link

Choose a reason for hiding this comment

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

This also affects the refreshTokenOnFocus, but do we want that? Because those cases can be a race to finish setting the cookie before any external data fetching runs, it seems prudent to use the available token then?

Copy link
Member Author

Choose a reason for hiding this comment

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

🤔

Comment on lines +380 to +381
// Prefer synchronous read to avoid microtask overhead when token is already resolved
const cachedToken = cacheResult.entry.resolvedToken ?? (await cacheResult.entry.tokenResolver);
Copy link

Choose a reason for hiding this comment

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

As I mentioned in chat, when I made the comment about this I didn't think it through fully. To get the full benefits, we'd have to make sure _getToken/getToken itself to be synchronous when data is already available (or maybe more likely add the .status and .value/.reason fields to the promise).

This likely only makes sense if/when we decide to expose this promise to the end user so they can use it though.

I see you've used resolvedToken as the way to be able to have a background refetch running while still reading the currently cached token though so this still has immediate value. That was a bit unclear at first, but I think it makes sense, will need to think some more on it.

Copy link
Member Author

Choose a reason for hiding this comment

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

Agreed. And yeah, right now the value is key to allow for returning the stale value, while we wait for the poller to do it's thing

@nikosdouvlis nikosdouvlis force-pushed the vincent-and-the-doctor branch from d24d455 to 12a12f5 Compare December 8, 2025 17:40
@nikosdouvlis nikosdouvlis deleted the branch main December 8, 2025 19:21
@jacekradko jacekradko reopened this Dec 8, 2025
@jacekradko jacekradko changed the base branch from vincent-and-the-doctor to main December 8, 2025 23:19
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 (2)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (1)

543-544: Consider using a helper to generate mock JWTs consistently.

The manually crafted newMockJwt works for this test since it's comparing raw strings, but for maintainability, consider using the createJwtWithTtl helper (from tokenCache.test.ts) or a shared fixture to ensure JWT claims are always valid and consistent across tests.

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

210-227: SWR logic is sound, but consider clarifying leeway behavior.

The implementation correctly:

  1. Evicts tokens with ≤5s remaining (forcing synchronous fetch)
  2. Signals needsRefresh when remaining TTL < effective leeway (minimum 15s)
  3. Returns the cached entry immediately regardless of staleness

However, the leeway parameter is effectively ignored when < 15s due to the floor at MIN_REMAINING_TTL_IN_SECONDS. While this is documented in the JSDoc, callers passing values like 10s (the default) may not realize their value has no effect.

Consider either:

  • Raising DEFAULT_LEEWAY to 15s to match the minimum, or
  • Adding a debug log when the provided leeway is floored

This is a minor clarity improvement and not blocking.

📜 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 ff335a0 and b1104ce.

📒 Files selected for processing (7)
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts (20 hunks)
  • packages/clerk-js/src/core/auth/AuthCookieService.ts (1 hunks)
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts (2 hunks)
  • packages/clerk-js/src/core/resources/Session.ts (2 hunks)
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts (4 hunks)
  • packages/clerk-js/src/core/tokenCache.ts (9 hunks)
  • packages/shared/src/types/session.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{js,jsx,ts,tsx}

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

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

Files:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}

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

Use Prettier for consistent code formatting

Files:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
packages/**/src/**/*.{ts,tsx}

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

TypeScript is required for all packages

Files:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
**/*.{ts,tsx,js,jsx}

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

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

Files:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.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/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
**/*.ts?(x)

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

Use proper TypeScript error types

Files:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.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:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
**/*.{js,ts,jsx,tsx}

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

Use ESLint with custom configurations tailored for different package types

Files:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.ts
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}

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

Use Prettier for code formatting across all packages

Files:

  • packages/shared/src/types/session.ts
  • packages/clerk-js/src/core/auth/AuthCookieService.ts
  • packages/clerk-js/src/core/auth/SessionCookiePoller.ts
  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/tokenCache.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
  • packages/clerk-js/src/core/resources/Session.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:

  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
**/*.{test,spec,e2e}.{ts,tsx,js,jsx}

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

Use real Clerk instances for integration tests

Files:

  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
**/*.test.{ts,tsx}

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

Use React Testing Library for component testing

Files:

  • packages/clerk-js/src/core/__tests__/tokenCache.test.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
🧬 Code graph analysis (5)
packages/clerk-js/src/core/auth/AuthCookieService.ts (1)
packages/clerk-js/src/core/resources/Session.ts (1)
  • token (402-413)
packages/clerk-js/src/core/auth/SessionCookiePoller.ts (1)
packages/astro/src/async-local-storage.client.ts (1)
  • run (17-19)
packages/clerk-js/src/core/tokenCache.ts (1)
packages/clerk-js/src/core/auth/SessionCookiePoller.ts (1)
  • POLLER_INTERVAL_IN_MS (7-7)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (4)
packages/clerk-js/src/test/core-fixtures.ts (1)
  • clerkMock (249-256)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (440-440)
packages/react/src/isomorphicClerk.ts (1)
  • session (721-727)
packages/clerk-js/src/core/resources/Session.ts (2)
  • Session (44-439)
  • token (402-413)
packages/clerk-js/src/core/resources/Session.ts (3)
packages/clerk-js/src/core/tokenCache.ts (1)
  • SessionTokenCache (440-440)
packages/clerk-js/src/core/events.ts (2)
  • eventBus (32-32)
  • events (7-15)
packages/clerk-js/src/core/resources/Token.ts (1)
  • Token (7-57)
⏰ 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). (28)
  • GitHub Check: Integration Tests (billing, chrome, RQ)
  • GitHub Check: Integration Tests (nextjs, chrome, 15)
  • GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
  • GitHub Check: Integration Tests (quickstart, chrome, 16)
  • GitHub Check: Integration Tests (machine, chrome, RQ)
  • GitHub Check: Integration Tests (nextjs, chrome, 16)
  • GitHub Check: Integration Tests (quickstart, chrome, 15)
  • GitHub Check: Integration Tests (billing, chrome)
  • GitHub Check: Integration Tests (machine, chrome)
  • GitHub Check: Integration Tests (custom, chrome)
  • GitHub Check: Integration Tests (nuxt, chrome)
  • GitHub Check: Integration Tests (ap-flows, chrome)
  • GitHub Check: Integration Tests (handshake, chrome)
  • GitHub Check: Integration Tests (vue, chrome)
  • GitHub Check: Integration Tests (react-router, chrome)
  • GitHub Check: Integration Tests (tanstack-react-start, chrome)
  • GitHub Check: Integration Tests (astro, chrome)
  • GitHub Check: Integration Tests (handshake:staging, chrome)
  • GitHub Check: Integration Tests (localhost, chrome)
  • GitHub Check: Integration Tests (sessions:staging, chrome)
  • GitHub Check: Integration Tests (sessions, chrome)
  • GitHub Check: Integration Tests (express, chrome)
  • GitHub Check: Integration Tests (generic, chrome)
  • GitHub Check: Formatting | Dedupe | Changeset
  • GitHub Check: Build Packages
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: semgrep-cloud-platform/scan
  • GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (15)
packages/shared/src/types/session.ts (1)

343-351: Well-documented internal API addition for SWR behavior.

The refreshIfStale option is properly marked as @internal with clear documentation explaining its purpose. This enables the token poller to proactively refresh tokens before they expire without exposing this mechanism to public consumers.

packages/clerk-js/src/core/auth/AuthCookieService.ts (1)

165-166: Correct use of refreshIfStale for proactive token refresh.

This ensures the poller and focus handler fetch fresh tokens when the cached token is within the leeway window. The focus handler's use of updateCookieImmediately: true (line 150) mitigates the race condition concern from previous reviews by ensuring the cookie is updated via microtask before external data-fetching libraries refetch.

packages/clerk-js/src/core/auth/SessionCookiePoller.ts (1)

6-7: Good: Exposing poller interval as a constant for cross-module alignment.

Exporting POLLER_INTERVAL_IN_MS enables the token cache to use the same interval for its "hard cutoff" logic, ensuring tokens aren't returned when they'll expire before the next poll opportunity. The 5-second interval with numeric separator is clear and readable.

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

421-578: Comprehensive SWR behavior test coverage.

The test suite effectively validates the stale-while-revalidate semantics:

  • Immediate stale token return with background refresh
  • Graceful degradation on network failures
  • Retry behavior after failures
  • Successful refresh propagation

The use of vi.advanceTimersByTime(46 * 1000) correctly positions the token in the leeway window (14s remaining < 15s threshold).

packages/clerk-js/src/core/__tests__/tokenCache.test.ts (4)

540-688: Thorough SWR leeway behavior tests with clear boundary conditions.

The tests effectively validate:

  • Fresh tokens return needsRefresh=false
  • Tokens within leeway return needsRefresh=true
  • Custom leeway values are honored when larger than the 15s minimum
  • The 15s minimum threshold is enforced even with leeway=0

The time-based assertions (e.g., 44s elapsed = 16s remaining vs. 46s elapsed = 14s remaining) clearly demonstrate the boundary behavior.


806-832: Critical: Hard cutoff test validates token expiration safety.

This test ensures tokens with less than the poller interval remaining (5s) are not returned, preventing race conditions where a "valid" token expires before the next refresh opportunity. The progression from 6s → 4s → 0s remaining with expected results (token → undefined → undefined) is well-designed.


1010-1063: Good coverage for resolvedToken synchronous access pattern.

The tests validate both scenarios:

  1. Token resolution timing: resolvedToken is undefined while pending, then populated after resolution
  2. Pre-resolved tokens: resolvedToken can be supplied upfront for hydration scenarios (e.g., from lastActiveToken)

This enables synchronous reads post-resolution, supporting the SWR pattern.


1065-1176: Multi-session isolation tests correctly updated for new result shape.

The access pattern changes (result.entry.tokenResolver, result.entry.tokenId) are consistent with the TokenCacheGetResult interface. The tests continue to validate that tokens from different sessions are properly isolated and broadcast synchronization works correctly.

packages/clerk-js/src/core/resources/Session.ts (4)

371-390: SWR implementation looks correct.

The logic correctly implements stale-while-revalidate semantics:

  • When needsRefresh is true but refreshIfStale is false (default), callers get the stale token immediately without blocking
  • The poller (using refreshIfStale: true) handles background refresh
  • Synchronous read via resolvedToken avoids microtask overhead for already-resolved tokens

This addresses the past review concerns about concurrent calls since normal getToken() calls no longer await a potentially in-flight background refresh.


392-400: Clean helper extraction.

The method properly encapsulates token creation logic. The explicit return type annotation aligns with coding guidelines.


402-413: Event dispatch logic is well-structured.

The conditional update of lastActiveToken only when token.jwt exists correctly handles the signed-out case where the token has an empty raw string. The TokenUpdate event is still emitted to notify listeners of the state.


415-433: Token fetch flow handles deduplication correctly.

Caching the promise immediately before awaiting prevents duplicate concurrent requests. Errors correctly propagate to the retry wrapper in getToken.

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

51-58: Well-defined interface for the new return type.

The TokenCacheGetResult interface cleanly encapsulates the SWR semantics with the needsRefresh flag allowing callers to decide whether to trigger a background refresh.


355-358: Synchronous read optimization implemented correctly.

Storing resolvedToken after the promise resolves allows callers to bypass the microtask queue when reading already-resolved tokens. This is referenced in Session.ts where it's used with nullish coalescing: cacheResult.entry.resolvedToken ?? (await cacheResult.entry.tokenResolver).


276-288: Broadcast handler correctly adapted to new interface.

The comparison logic properly accesses result.entry.tokenResolver after the interface change.

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.

5 participants