Code
Save this as public/sw.js. Next.js serves the public folder at the site root, so the worker is registered as /sw.js.
js
// public/sw.js: Next.js serves public/ at the site root, so register it as "/sw.js".
const CACHE = "app-v2"; // bump the name to drop entries an older worker saved
const OFFLINE_URL = "/offline";
// Your sign-in, sign-out, callback and billing routes. The worker never touches them.
const NEVER_CACHE = ["/api/auth", "/login", "/logout", "/account", "/billing"];
function isAuthPath(url) {
return NEVER_CACHE.some((p) => url.pathname === p || url.pathname.startsWith(p + "/"));
}
function canCache(request, response) {
if (request.method !== "GET" || isAuthPath(new URL(request.url))) return false;
// 301/302/307 and "opaqueredirect" (status 0) fail this check.
if (!response || response.status !== 200) return false;
// A 200 that came after a redirect would be saved under the first URL.
if (response.type !== "basic" || response.redirected) return false;
return !/no-store/i.test(response.headers.get("Cache-Control") || "");
}
async function networkFirst(request) {
try {
const response = await fetch(request);
if (canCache(request, response)) {
const cache = await caches.open(CACHE);
await cache.put(request, response.clone());
}
return response;
} catch (err) {
const cached = await caches.match(request);
if (cached) return cached;
if (request.mode === "navigate") {
const offline = await caches.match(OFFLINE_URL);
if (offline) return offline;
}
throw err;
}
}
self.addEventListener("install", (event) => {
event.waitUntil(caches.open(CACHE).then((cache) => cache.add(OFFLINE_URL)));
});
self.addEventListener("activate", (event) => {
event.waitUntil((async () => {
for (const key of await caches.keys()) if (key !== CACHE) await caches.delete(key);
await self.clients.claim();
})());
});
self.addEventListener("fetch", (event) => {
const { request } = event;
const url = new URL(request.url);
if (request.method !== "GET" || url.origin !== self.location.origin) return;
if (isAuthPath(url)) return; // network only: the browser handles it as if no worker existed
event.respondWith(networkFirst(request));
});
// Lets a Node test load this file; ignored in the browser.
if (typeof module !== "undefined") module.exports = { canCache, isAuthPath, networkFirst };Why it happens
A navigation request inside a service worker uses manual redirect mode. A 302 from the server reaches the worker as an "opaqueredirect" response with status 0. A worker that caches every response it gets will store that redirect and replay it later, even after the user signs in or the plan changes.
A second trap is response.redirected. When a fetch follows a redirect, the final page comes back with status 200, but it is filed under the first URL. A status check alone will not catch it.
Steps
- Put your sign-in, sign-out, callback and billing paths in
NEVER_CACHE. The fetch handler returns early for them, so the browser goes straight to the network. - Every other same-origin GET goes through
networkFirst. A fresh response is used when the network works, and the cache is only a fallback. canCachesaves a response only if it is a200, of typebasic, not redirected, and not markedno-store.- Change
CACHE(for example fromapp-v1toapp-v2) when you ship this fix. Theactivatestep deletes every other cache, which removes redirects already stored on users' devices. - Create an
/offlinepage. It is cached at install and shown for navigations when there is no network and no cached copy.
Pitfalls
- Users only get the new worker after it installs and activates. Test with "Update on reload" in the browser's Application panel, then check Cache Storage.
- Add
Cache-Control: no-storeon auth responses at the server as well. It also protects the browser's own HTTP cache, not only this worker. - Network-first sends a request for every asset. For hashed files under
/_next/static/you can switch to cache-first, but keep the samecanCachecheck. - Path matching is by prefix with a
/boundary, so/login/resetis skipped but/loginhelpis not. List every auth path your app really uses.
Seen on: Stack Overflow ·
Related service: Next.js web app (MVP)