Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content

fix(clerk-js): clear cached tokens and refresh timers for removed sessions - #11004

Merged
wobsoriano merged 4 commits into
mainfrom
rob/clear-removed-session-token-cache
Nov 25, 2026
Merged

wobsoriano merged 4 commits into
mainfrom
rob/clear-removed-session-token-cache

Conversation

@wobsoriano

@wobsoriano wobsoriano commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

Description

When a session is removed or leaves signed-in status through a client update outside JS sign-out (such as native sign-out in @clerk/expo, cross-tab sign-out, or backend revocation), SessionTokenCache kept that session's cached tokens and 43-second proactive refresh timers. Those timers still fired POST /v1/client/sessions/:id/tokens for already-removed sessions, returning 404 resource_not_found or 401 authentication_invalid.

Client.fromJSON now calls SessionTokenCache.clear() before rebuilding this.sessions whenever any previously signed-in session leaves 'active' | 'pending' status, matching Session.end and Session.remove. Surviving signed-in sessions immediately re-hydrate in new Session(...) while preserving fresher piggybacked tokens via shouldKeepExistingLastActiveToken. Session now also skips cache hydration for non-signed-in sessions and avoids caching tokens or emitting token:update if an in-flight token fetch or background refresh settles after removal.

Verified on an iOS 27 simulator and Android API 36 emulator in the Expo native fixture app with a temporary on-screen /tokens fetch monitor (not committed in this PR). After signing in and signing out through the native UserButton, before fires POST /v1/client/sessions/:id/tokens -> 401 (authentication_invalid) at 35-37s while after fires 0 requests through 46-48s.

iOSAndroid
Before
before-ios.mp4
before-android.mp4
After
after-ios.mp4
after-android.mp4

🤖 Generated with Antigravity under Rob's supervision.

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:

@vercel

vercel Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
clerk-js-sandbox Ready Ready Preview Nov 25, 2026 6:29am UTC
mosaic-docs Ready Ready Preview Nov 25, 2026 6:29am UTC
swingset Ready Ready Preview Nov 25, 2026 6:29am UTC

Request Review

@coderabbitai

coderabbitai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Client updates now clear the session-token cache when a previously signed-in session is absent from the incoming signed-in sessions. Session token hydration, cache writes, event dispatch, and background refresh now depend on the session remaining active or pending and, when a client exists, appearing in its signed-in sessions. Tests cover removed sessions and token operations that complete after removal.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • clerk/javascript#10390: Changes Session token emission and hydration conditions, which overlap with the token handling paths updated here.

Suggested reviewers: nikosdouvlis, bratsos

Merge Risk: Minimal · up to c293f

This change clears cached tokens and cancels refresh timers for sessions removed through a client update. That stops stray token requests that return 404 or 401. No actionable merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the change: clearing cached session tokens and proactive refresh timers when sessions are removed. The changeset covers that. It also carries a 'fix(clerk-js):' prefix, which matches t…
Description check Passed The description states the bug: cached tokens and 43-second refresh timers survived session removal done outside JS sign-out. It names the affected files and methods (Client.fromJSON, SessionTokenCach…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the change: clearing cached session tokens and proactive refresh timers when sessions are removed. The changeset covers that. It also carries a 'fix(clerk-js):' prefix, which matches the bug-fix checklist item and names the affected package. The title is specific and maps to the main change.

Full details: Description check

Explanation

The description states the bug: cached tokens and 43-second refresh timers survived session removal done outside JS sign-out. It names the affected files and methods (Client.fromJSON, SessionTokenCache.clear, Session), the fix, and the native Expo verification with before and after results. It is directly related to the changeset.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Linked repositories: This review skipped 6 repositories. Cross-repository analysis may be incomplete. Check linked repository access and settings.

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 0c45e9a and c293f41.

Files selected for processing: 4

  • .changeset/clear-removed-session-token-cache.md
  • packages/clerk-js/src/core/resources/Client.ts
  • packages/clerk-js/src/core/resources/Session.ts
  • packages/clerk-js/src/core/resources/__tests__/Session.test.ts
Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

Included review availability: This review used your included allowance. 4 included reviews remain after this review. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour.

@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 4810c49

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 4 packages
Name Type
@clerk/clerk-js Patch
@clerk/chrome-extension Patch
@clerk/electron Patch
@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

@pkg-pr-new

pkg-pr-new Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@clerk/astro

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

@clerk/backend

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

@clerk/chrome-extension

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

@clerk/clerk-js

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

@clerk/electron

npm i https://pkg.pr.new/@clerk/electron@11004

@clerk/electron-passkeys

npm i https://pkg.pr.new/@clerk/electron-passkeys@11004

@clerk/eslint-plugin

npm i https://pkg.pr.new/@clerk/eslint-plugin@11004

@clerk/expo

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

@clerk/expo-biometrics

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

@clerk/expo-google-signin

npm i https://pkg.pr.new/@clerk/expo-google-signin@11004

@clerk/expo-native-components

npm i https://pkg.pr.new/@clerk/expo-native-components@11004

@clerk/expo-passkeys

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

@clerk/express

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

@clerk/fastify

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

@clerk/hono

npm i https://pkg.pr.new/@clerk/hono@11004

@clerk/localizations

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

@clerk/mosaic

npm i https://pkg.pr.new/@clerk/mosaic@11004

@clerk/nextjs

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

@clerk/nuxt

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

@clerk/react

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

@clerk/react-router

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

@clerk/shared

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

@clerk/tanstack-react-start

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

@clerk/testing

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

@clerk/ui

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

@clerk/upgrade

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

@clerk/vue

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

commit: c293f41

@github-actions

Copy link
Copy Markdown
Contributor

API Changes Report

Generated by Break Check on 2026-11-25T06:47:39.847Z

Summary

Metric Count
Packages analyzed 20
Packages with changes 0
🔴 Breaking changes 0
🟡 Non-breaking changes 0
🟢 Additions 0

No API Changes Detected

All packages have stable APIs with no detected changes.


Report generated by Break Check

Last ran on c293f41.

@blacksmith-sh

blacksmith-sh Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Matches Removed session stops background token refresh

After a client refetch dropped the only session, base fired POST /tokens -> 401 at 42.7s; head sent none in 50s.

Merge-base

Only session removed

This PR c293f414

Only session removed

Also checked · 2 match

Matches Surviving session keeps refreshing when another is removed
Matches In-flight token fetch after removal is not cached or emitted

Proof on c293f414 · mocked: Clerk Frontend API (Removing a session out-of-band needs control over client responses; the sandbox'...) · Did Proof get it right? Yes · No

View full Proof report · React 👎 or comment @codesmith dismiss this proof to dismiss

@wobsoriano
wobsoriano requested a review from Ephem November 25, 2026 06:58

@Ephem Ephem left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Nice find, the fix looks safe. Left a comment with some analysis and a possible alternative solution, but feel free to merge as is.

);
const previousTokens = new Map(this.sessions.map(session => [session.id, session.lastActiveToken]));
if (previousSignedInIds.some(id => !nextSignedInIds.has(id))) {
SessionTokenCache.clear();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Note that this clears the entire cache in a multi-session scenario, which works (it refetches) but is wasteful.

);
const previousTokens = new Map(this.sessions.map(session => [session.id, session.lastActiveToken]));
if (previousSignedInIds.some(id => !nextSignedInIds.has(id))) {
SessionTokenCache.clear();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is just a suggestion, I think the solution the PR is fine for a fix but I noted the whole model is slightly off which is why this bug happened in the first place.

This is a side effect in a fromJSON function, which felt a bit unexpected so I dug into it a bit. I realized that even more unexpected is that new Session(...) calls this.#hydrateCache(this.lastActiveToken);, which seeds the global cache and starts the timers.

This is a side effect in a constructor and I think that's the core cause of this bug, nothing really owns tearing that down when the session goes away, or in other words the ownership of the token cache is unclear, which is why you need the workarounds in this PR.

I think we should probably hoist ownership to clerk, since that's what owns the session lifecycle to start with, and let that both seed the cache/start timers and tear them down (likely in updateClient). I think that's a larger refactor though and there's more things we'd want to tweak if we do that.

One thing we could do now which also solves the multi-session thing is hoisting only the ownership of the teardown as a start:

  • SessionTokenCache starts keeping the sessionId of each entry on creation
  • SessionTokenCache gains a .retainIds(sessionIds) function that clears all ids not passed in
  • We do SessionTokenCache.retainIds(newClient.signedInSessions.map(s => s.id)) in updateClient

We would keep the hydration in the constructor as that's a larger change, we would also still need:

  • The #isSignedInOnCurrentClient checks in this PR
  • Keep calling clear() in destroy and __internal_signOut, since those don't go through updateClient

This would move the teardown to the thing that actually knows what to tear down and owns the timing of things.

This is a slightly larger (and possibly scarier?) change though.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Makes total sense on the ownership model. new Session(...) hydrating the global cache and starting timers in a constructor is what makes teardown awkward.

We actually tried per-session eviction on SessionTokenCache + updateClient in an earlier commit on this PR, then trimmed it back to SessionTokenCache.clear() in Client.fromJSON to keep the patch small and match what Session.remove() already does. Surviving sessions still re-hydrate their default token immediately in the loop, so only custom templates or explicit-org tokens refetch once.

Agreed that hoisting token cache lifecycle ownership (or retainIds in updateClient) is much cleaner as a dedicated follow-up. Going to merge this as-is to stop the 401/404s first.

🤖 Generated with Antigravity under Rob's supervision.

@wobsoriano

Copy link
Copy Markdown
Member Author

Nice find, the fix looks safe. Left a comment with some analysis and a possible alternative solution, but feel free to merge as is.

Thanks for the review and approval! Your comments makes sense and they're noted ❤️

@wobsoriano
wobsoriano merged commit 1266855 into main Nov 25, 2026
110 checks passed
@wobsoriano
wobsoriano deleted the rob/clear-removed-session-token-cache branch November 25, 2026 16:49

This branch was successfully deployed

2 active deployments
Preview – swingset — c293f414 Deployed Nov 25, 2026 by vercel[bot]
Preview – clerk-js-sandbox — c293f414 Deployed Nov 25, 2026 by vercel[bot]
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.

2 participants