Repository navigation
fix(clerk-js): clear cached tokens and refresh timers for removed sessions - #11004
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
🦋 Changeset detectedLatest commit: 4810c49 The changes in this PR will be included in the next version bump. This PR includes changesets to release 4 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 |
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/electron
@clerk/electron-passkeys
@clerk/eslint-plugin
@clerk/expo
@clerk/expo-biometrics
@clerk/expo-google-signin
@clerk/expo-native-components
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/hono
@clerk/localizations
@clerk/mosaic
@clerk/nextjs
@clerk/nuxt
@clerk/react
@clerk/react-router
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/ui
@clerk/upgrade
@clerk/vue
commit: |
API Changes Report
Summary
No API Changes DetectedAll packages have stable APIs with no detected changes. Report generated by Break Check Last ran on |
|
Ephem
left a comment
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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(); |
There was a problem hiding this comment.
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:
SessionTokenCachestarts keeping thesessionIdof each entry on creationSessionTokenCachegains a.retainIds(sessionIds)function that clears all ids not passed in- We do
SessionTokenCache.retainIds(newClient.signedInSessions.map(s => s.id))inupdateClient
We would keep the hydration in the constructor as that's a larger change, we would also still need:
- The
#isSignedInOnCurrentClientchecks in this PR - Keep calling
clear()indestroyand__internal_signOut, since those don't go throughupdateClient
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.
There was a problem hiding this comment.
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.
Thanks for the review and approval! Your comments makes sense and they're noted ❤️ |


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),SessionTokenCachekept that session's cached tokens and 43-second proactive refresh timers. Those timers still firedPOST /v1/client/sessions/:id/tokensfor already-removed sessions, returning404 resource_not_foundor401 authentication_invalid.Client.fromJSONnow callsSessionTokenCache.clear()before rebuildingthis.sessionswhenever any previously signed-in session leaves'active' | 'pending'status, matchingSession.endandSession.remove. Surviving signed-in sessions immediately re-hydrate innew Session(...)while preserving fresher piggybacked tokens viashouldKeepExistingLastActiveToken.Sessionnow also skips cache hydration for non-signed-in sessions and avoids caching tokens or emittingtoken:updateif 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
/tokensfetch monitor (not committed in this PR). After signing in and signing out through the nativeUserButton, before firesPOST /v1/client/sessions/:id/tokens -> 401 (authentication_invalid)at 35-37s while after fires 0 requests through 46-48s.before-ios.mp4
before-android.mp4
after-ios.mp4
after-android.mp4
🤖 Generated with Antigravity under Rob's supervision.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change