Skip to content

feat(clerk-js): experimental SWR initialization for faster page loads#8153

Draft
nikosdouvlis wants to merge 1 commit intomainfrom
nikos/clerkjs-swr-init
Draft

feat(clerk-js): experimental SWR initialization for faster page loads#8153
nikosdouvlis wants to merge 1 commit intomainfrom
nikos/clerkjs-swr-init

Conversation

@nikosdouvlis
Copy link
Member

Why

Clerk initialization blocks on the /client API response, which is a full server roundtrip (500ms-2s). For returning users, this means a loading spinner on every page load even though we already have their session data from the previous visit. Auth providers are infrastructure, and infrastructure that initializes faster wins.

What

Adds an opt-in experimental.swr flag to Clerk.load() that enables stale-while-revalidate initialization. When enabled, clerk-js:

  1. Reads a cached Client snapshot from localStorage (saved on previous successful /client response)
  2. Checks if the __session cookie JWT is still valid
    • Valid (SSR apps always have one from middleware refresh, CSR within ~60s): emit ready instantly, zero network
    • Expired: call getToken() (edge-routed, fast) to validate session liveness
  3. Emits ready/degraded with cached data while /client fetches in the background
  4. Silently swaps to fresh /client data when it arrives

The cache is scoped by publishable key, versioned for schema safety, strips JWTs and signIn/signUp flow state before saving, and clears on sign-out (including cross-tab via BroadcastChannel).

Key design decisions

  • Token validation gate: never boots with an unvalidated session. Either the cookie JWT is fresh, or getToken confirms liveness.
  • 4xx from getToken = session revoked, cache discarded, falls through to normal flow
  • Transient errors (5xx/network) = emit degraded with cached data, same as existing degraded behavior
  • Cached environment is restored from localStorage before emitting ready so components have valid displayConfig/authConfig
  • Session fallback on background /client swap is scoped to SWR context only, doesn't change updateClient behavior for other callers
  • Cache save uses updatedAt dedup guard to avoid redundant localStorage writes

Test plan

  • 10 unit tests for SWR cache module (save/read/clear/sanitization/token expiry)
  • 8 unit tests for SWR init branch (disabled, no cache, valid JWT, expired+getToken, 401, transient error, corrupted cache, session fallback)
  • 3 integration tests (cache on reload, clear on sign-out, revoked session fallback)
  • 100 existing clerk.test.ts tests still passing
  • Manual test: enable experimental: { swr: true }, sign in, reload, verify instant load

🤖 Generated with Claude Code

…oads

Clerk initialization blocks on /client (slow server roundtrip). This adds
an opt-in experimental.swr flag that lets clerk-js initialize immediately
from a cached client snapshot, validated by a fast token check, then
silently swap to fresh /client data in the background.

The flow: read cached client from localStorage, check if the __session
cookie JWT is still valid (SSR apps always have one from middleware
refresh). If valid, emit ready instantly with zero network. If expired,
call getToken (edge-routed, fast) to validate session liveness. If
revoked (4xx), discard cache and fall through to normal flow. If
transient error, emit degraded with cached data.

Cache is scoped by publishable key, versioned for schema safety, strips
JWTs and signIn/signUp state before saving, and clears on sign-out
(including cross-tab via BroadcastChannel).
@changeset-bot
Copy link

changeset-bot bot commented Mar 23, 2026

⚠️ No Changeset found

Latest commit: a4cddf1

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

@vercel
Copy link

vercel bot commented Mar 23, 2026

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

Project Deployment Actions Updated (UTC)
clerk-js-sandbox Ready Ready Preview, Comment Mar 23, 2026 2:43pm

Request Review

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.

1 participant