-
Notifications
You must be signed in to change notification settings - Fork 424
feat(clerk-js): Stale-while-revalidate session token #7317
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
🦋 Changeset detectedLatest commit: c58d1f4 The changes in this PR will be included in the next version bump. This PR includes changesets to release 20 packages
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 |
📝 WalkthroughWalkthroughImplements stale‑while‑revalidate for session tokens. TokenCache.get now returns a TokenCacheGetResult with 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. 📜 Recent review detailsConfiguration used: Repository YAML (base), Organization UI (inherited) Review profile: CHILL Plan: Pro Disabled knowledge base sources:
📒 Files selected for processing (2)
🧰 Additional context used📓 Path-based instructions (10)**/*.{js,jsx,ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{js,jsx,ts,tsx,json,md,yml,yaml}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/src/**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{ts,tsx,js,jsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
packages/**/src/**/*.{ts,tsx,js,jsx}📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.ts?(x)📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Files:
**/*.{ts,tsx}📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
Files:
**/*.{js,ts,jsx,tsx}📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Files:
**/*.{js,ts,jsx,tsx,json,md,yml,yaml}📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Files:
**/*⚙️ CodeRabbit configuration file
Files:
🧬 Code graph analysis (2)packages/clerk-js/src/core/resources/Session.ts (6)
packages/clerk-js/src/core/tokenCache.ts (1)
⏰ 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). (25)
🔇 Additional comments (6)
✏️ Tip: You can disable this entire section by setting Comment |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
| const tokenResolver = Token.create(path, params, false); | ||
|
|
||
| // Cache the promise immediately to prevent concurrent calls from triggering duplicate requests | ||
| SessionTokenCache.set({ tokenId, tokenResolver }); |
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.
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.
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.
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.
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.
Also expanded the test coverage of the SWR behavior
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/react
@clerk/react-router
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/ui
@clerk/upgrade
@clerk/vue
commit: |
Ephem
left a comment
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.
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) { |
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.
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.
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.
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.
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.
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); |
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.
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.
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.
🤔 In agreement here, this effectively forces leeway to always be equal to or greater than MIN_REMAINING_TTL_IN_SECONDS, do we want that value to be 5 or 15 going forward?
| 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 }); |
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.
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?
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.
🤔
| // Prefer synchronous read to avoid microtask overhead when token is already resolved | ||
| const cachedToken = cacheResult.entry.resolvedToken ?? (await cacheResult.entry.tokenResolver); |
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.
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.
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.
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
d24d455 to
12a12f5
Compare
- Trigger background refresh when needsRefresh is true, without requiring refreshIfStale option. Guarantees cache revalidation without relying solely on the poller. - Add #refreshTokenInBackground() that doesn't cache pending promise, allowing concurrent getToken() calls to return stale token while refresh is in progress. - Track in-flight background refreshes to prevent duplicate requests. - Rename DEFAULT_LEEWAY to BACKGROUND_REFRESH_THRESHOLD_IN_SECONDS with clear documentation about 15s minimum and rate limiting warning. - Add comprehensive JSDoc for leewayInSeconds option explaining minimum value, default, and rate limiting considerations.
Add upgrade guide entries for: - getToken `leewayInSeconds` minimum of 15 seconds - stale-while-revalidate pattern for session tokens
- Test refreshIfStale: true forces synchronous refresh when token is stale - Test refreshIfStale: true with fresh token returns cached value - Test leewayInSeconds triggers earlier background refresh - Test minimum 15s leeway enforcement - Test no background refresh when token has sufficient TTL
|
!snapshot |
|
Hey @jacekradko - the snapshot version command generated the following package versions:
Tip: Use the snippet copy button below to quickly install the required packages. npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact |
- Rename option from leewayInSeconds to backgroundRefreshThreshold for clarity - Lower minimum threshold from 15s to 5s (poller interval) - Remove explicit refreshIfStale: false in AuthCookieService (default behavior) - Update tests and upgrade documentation
# Conflicts: # packages/clerk-js/bundlewatch.config.json
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
🤖 Fix all issues with AI agents
In `@packages/clerk-js/src/core/tokenCache.ts`:
- Line 79: The JSDoc for refreshThreshold in tokenCache.ts incorrectly states a
minimum of 15s; update the param description for refreshThreshold to reflect the
actual enforced minimum (POLLER_INTERVAL_IN_MS / 1000, i.e., 5s) or remove the
hardcoded "minimum" clause; reference the refreshThreshold param and
POLLER_INTERVAL_IN_MS constant and ensure the description matches the
Math.max(refreshThreshold, POLLER_INTERVAL_IN_MS / 1000) behavior used in the
code.
📜 Review details
Configuration used: Repository YAML (base), Organization UI (inherited)
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 (2)
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/tokenCache.ts
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
All code must pass ESLint checks with the project's configuration
Files:
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/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:
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/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/resources/__tests__/Session.test.tspackages/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)
Files:
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/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/resources/__tests__/Session.test.tspackages/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:
packages/clerk-js/src/core/resources/__tests__/Session.test.ts
**/*.ts?(x)
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
Files:
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/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:
packages/clerk-js/src/core/resources/__tests__/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
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Implement type guards forunknowntypes using the patternfunction isType(value: unknown): value is Type
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details in classes
Useprotectedfor inheritance hierarchies
Usepublicexplicitly 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 likeOmit,Partial, andPickfor 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@exampletags
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
Useconst assertionswithas constfor literal types
Usesatisfiesoperator 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/clerk-js/src/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/tokenCache.ts
**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Use React Testing Library for component testing
Files:
packages/clerk-js/src/core/resources/__tests__/Session.test.ts
**/*.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Use ESLint with custom configurations tailored for different package types
Files:
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/tokenCache.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/clerk-js/src/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/tokenCache.ts
**/*
⚙️ CodeRabbit configuration file
If there are no tests added or modified as part of the PR, please suggest that tests be added to cover the changes.
**/*: Only comment on issues that would block merging, ignore minor or stylistic concerns.
Restrict feedback to errors, security risks, or functionality-breaking problems.
Do not post comments on code style, formatting, or non-critical improvements.
Keep reviews short: flag only issues that make the PR unsafe to merge.
Group similar issues into a single comment instead of posting multiple notes.
Skip repetition: if a pattern repeats, mention it once at a summary level only.
Do not add general suggestions, focus strictly on merge-blocking concerns.
If there are no critical problems, respond with minimal approval (e.g., 'Looks good'). Do not add additional review.
Avoid line-by-line commentary unless it highlights a critical bug or security hole.
Highlight only issues that could cause runtime errors, data loss, or severe maintainability issues.
Ignore minor optimization opportunities, focus solely on correctness and safety.
Provide a top-level summary of critical blockers rather than detailed per-line notes.
Comment only when the issue must be resolved before merge, otherwise remain silent.
When in doubt, err on the side of fewer comments, brevity and blocking issues only.
Avoid posting any refactoring issues.
Files:
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/tokenCache.ts
🧬 Code graph analysis (1)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (3)
packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache(452-452)packages/react/src/isomorphicClerk.ts (1)
session(722-728)packages/clerk-js/src/core/resources/Session.ts (2)
Session(44-499)token(422-433)
⏰ 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). (25)
- GitHub Check: Integration Tests (nextjs, chrome, 16, RQ)
- GitHub Check: Integration Tests (quickstart, chrome, 16)
- GitHub Check: Integration Tests (billing, chrome, RQ)
- GitHub Check: Integration Tests (quickstart, chrome, 15)
- GitHub Check: Integration Tests (nextjs, chrome, 16)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (machine, chrome, RQ)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (custom, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (handshake, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (sessions:staging, chrome)
- GitHub Check: Integration Tests (handshake:staging, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (1)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (1)
422-737: Comprehensive SWR test coverage.The test suite thoroughly covers the stale-while-revalidate behavior including edge cases for background refresh failures, retry logic, threshold configuration, and the
refreshIfStaleoption. Timer calculations are correct relative to the mock JWT's 60s TTL.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
| * @param cacheKeyJSON - Object containing tokenId and optional audience to identify the cached entry | ||
| * @param leeway - Optional seconds before expiration to treat token as expired (default: 10s). Combined with 5s sync leeway. | ||
| * @returns The cached TokenCacheEntry if found and valid, undefined otherwise | ||
| * @param refreshThreshold - Seconds before expiration to trigger background refresh (default: 15s, minimum: 15s). |
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.
JSDoc minimum value is incorrect.
The documentation states minimum: 15s but the code at line 232 enforces Math.max(refreshThreshold, POLLER_INTERVAL_IN_MS / 1000), which is 5s (the poller interval). The test at line 676-708 in Session.test.ts confirms thresholds below 15s work correctly.
Suggested fix
- * `@param` refreshThreshold - Seconds before expiration to trigger background refresh (default: 15s, minimum: 15s).
+ * `@param` refreshThreshold - Seconds before expiration to trigger background refresh (default: 15s, minimum: 5s).📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| * @param refreshThreshold - Seconds before expiration to trigger background refresh (default: 15s, minimum: 15s). | |
| * `@param` refreshThreshold - Seconds before expiration to trigger background refresh (default: 15s, minimum: 5s). |
🤖 Prompt for AI Agents
In `@packages/clerk-js/src/core/tokenCache.ts` at line 79, The JSDoc for
refreshThreshold in tokenCache.ts incorrectly states a minimum of 15s; update
the param description for refreshThreshold to reflect the actual enforced
minimum (POLLER_INTERVAL_IN_MS / 1000, i.e., 5s) or remove the hardcoded
"minimum" clause; reference the refreshThreshold param and POLLER_INTERVAL_IN_MS
constant and ensure the description matches the Math.max(refreshThreshold,
POLLER_INTERVAL_IN_MS / 1000) behavior used in the code.
|
!snapshot |
|
Hey @jacekradko - the snapshot version command generated the following package versions:
Tip: Use the snippet copy button below to quickly install the required packages. npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact
npm i @clerk/[email protected] --save-exact |
Description
This PR implements a stale-while-revalidate (SWR) pattern for session tokens in
getToken(). Instead of blocking on token refresh when a token is close to expiration, we return the cached token immediately and trigger a background refresh.Fixes: USER-4087
Dashboard testing PR: https://github.com/clerk/dashboard/pull/7990
How It Works
Key Behaviors
Configuration
The
backgroundRefreshThresholdoption (formerlyleewayInSeconds) controls when background refresh is triggered:Additional Options
refreshIfStale(internal): Whentrue, forces a blocking fetch instead of SWR behavior. Useful as an escape hatch when you absolutely need a fresh token and can wait for it.Implementation Details
Token Cache (
tokenCache.ts)get()returns{ entry, needsRefresh }instead of just the entryneedsRefreshsignals when background refresh should occurBroadcastChannelSession (
Session.ts)#refreshTokenInBackground(): Triggers refresh without blocking, doesn't cache the pending promise so concurrent calls still get the stale tokenresolvedTokenon cache entries enables synchronous reads (avoids microtask overhead)#backgroundRefreshInProgressSetAuthCookieService
refreshIfStale)refreshTokenOnFocusreturns cached token immediately to update cookie before SWR/similar libraries refetchBreaking Changes (Core 3)
leewayInSeconds→backgroundRefreshThresholdChecklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
New Features
Documentation
Tests
✏️ Tip: You can customize this high-level summary in your review settings.