HOW-TO

How to stop a Next.js service worker caching auth redirects

Published · Updated

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

  1. 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.
  2. Every other same-origin GET goes through networkFirst. A fresh response is used when the network works, and the cache is only a fallback.
  3. canCache saves a response only if it is a 200, of type basic, not redirected, and not marked no-store.
  4. Change CACHE (for example from app-v1 to app-v2) when you ship this fix. The activate step deletes every other cache, which removes redirects already stored on users' devices.
  5. Create an /offline page. 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-store on 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 same canCache check.
  • Path matching is by prefix with a / boundary, so /login/reset is skipped but /loginhelp is not. List every auth path your app really uses.

Seen on: Stack Overflow ·

Related service: Next.js web app (MVP)