Swoff Swoff

Service Worker Integration

How the service worker handles authenticated requests and cache invalidation on logout.

Service Worker Integration

Prerequisites: SW Template, Auth Store.

Principle: SW is Auth-Unaware

The service worker does not need to know about auth. It doesn't read tokens, check sessions, or manage identity. It just passes headers through.

This is by design:

  • Tokens stored in the SW would be lost when the SW is terminated
  • The SW has no DOM access — can't redirect to login
  • Keeping auth in the client layer is simpler and more secure

What the SW Does

Request typeX-SW-Cache-StrategySW behavior
Login / Logout / Registermutation (set by authenticatedFetch)Pass through, no caching
Token refreshmutationPass through, no caching
Authenticated read (e.g., /api/me)read (default for GET)Cache response, serve offline
Unauthenticated readreadCache response, serve offline

The SW template's fetch handler already handles this — see the SW Template.

Auth Endpoint Exclusion

Auth endpoints must reach the server every time — no caching. The generated auth-fetch.js isAuthUrl() checks these paths: /login, /logout, /register, /api/login, /api/logout, /api/register, plus your configured refreshPath and userEndpoint.

Logout Cache Invalidation

When auth is enabled, the generated SW template includes a CLEAR_RUNTIME_CACHE message handler. The client sends this message on logout:

// Generated for you — in your logout function
if ("serviceWorker" in navigator) {
  const registration = await navigator.serviceWorker.getRegistration();
  if (registration?.active) {
    registration.active.postMessage({ type: "CLEAR_RUNTIME_CACHE" });
  }
}

What NOT to Do in the SW

❌ Don'tWhy
Don't store tokens in the SWSW is terminated when idle — tokens are lost
Don't check auth in the fetch handlerAuth is the client's responsibility
Don't cache auth endpointsLogin/logout/refresh must reach the server
Don't try to redirect to login from SWSW has no DOM or navigation access

Background Sync Consideration

When the SW syncs queued mutations, cookie auth works by setting credentials: "same-origin" on fetches inside the SW. Bearer auth will not work in the SW (token is memory-only in the page). For bearer auth, call flushMutations() after re-login to drain the queue from the client context.

Next Steps

On this page