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 type | X-SW-Cache-Strategy | SW behavior |
|---|---|---|
| Login / Logout / Register | mutation (set by authenticatedFetch) | Pass through, no caching |
| Token refresh | mutation | Pass through, no caching |
Authenticated read (e.g., /api/me) | read (default for GET) | Cache response, serve offline |
| Unauthenticated read | read | Cache 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't | Why |
|---|---|
| Don't store tokens in the SW | SW is terminated when idle — tokens are lost |
| Don't check auth in the fetch handler | Auth is the client's responsibility |
| Don't cache auth endpoints | Login/logout/refresh must reach the server |
| Don't try to redirect to login from SW | SW 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
- Offline Auth State — the four auth states
- Mutation Queuing — queue writes behind auth
Swoff