A service worker sits between your users and your server and lives on after the page closes. That makes it a high-value target. Follow these rules.
Transport
- HTTPS everywhere, with HSTS. Service workers will not register on plain HTTP (except
localhost). - No mixed content.
The service worker script
- Serve
sw.jsfrom your own origin, from the narrowest path that works. Do not let user uploads end up in a folder where they could be registered as a worker. - Never import worker scripts from third-party CDNs you do not control.
- Serve it with
Cache-Control: no-cacheso a fix reaches everyone quickly. - Keep a kill switch ready: a version of
sw.jsthat unregisters itself (lifecycle).
Caching private data
- Never cache authenticated or personalised responses under shared keys. Only cache what any visitor could see, or include the user in the cache name and clear it on sign-out.
- Do not cache responses with
Cache-Control: privateorno-storeunless you know why. - On sign-out, clear user caches, IndexedDB and push subscriptions:
async function signOut() {
for (const k of await caches.keys()) if (k.startsWith('user-')) await caches.delete(k);
indexedDB.deleteDatabase('user-data');
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.getSubscription();
if (sub) { await fetch('/api/push/unsubscribe', { method: 'POST', body: JSON.stringify(sub) }); await sub.unsubscribe(); }
}
The Clear-Site-Data response header is a server-side alternative.
Content Security Policy
A CSP limits where scripts can come from, which protects the page and the worker it registers:
Content-Security-Policy: default-src 'self'; script-src 'self'; worker-src 'self'; connect-src 'self' https://api.example.com; img-src 'self' data:; manifest-src 'self'
Push
- Keep the VAPID private key on the server only.
- Tie subscriptions to accounts server-side; delete them on sign-out and on 404/410 responses.
- Do not put sensitive data in notification text; it shows on lock screens.
Third-party scripts
Every analytics or chat script runs with your page's privileges and can read your caches. Load as few as possible, and only after consent where required.