๐Ÿ”ฅ All-Access Pass โ€” $199 USD (Regular $499) ยท Unlock all 2,836 Astro themes โž”
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
Performanceโ€ขโ€ขBy Komal Nakrani

Astro Service Worker: Offline Support for a Static Site

Add an Astro service worker for offline support: cache-first for hashed /_astro/ assets, network-first for HTML, an offline fallback page, and safe updates.

#Astro#Service Worker#PWA#Offline

To add a service worker to Astro, write public/sw.js, register it with a small script in your base layout, and use two caching strategies: cache-first for the hashed files in /_astro/, which never change, and network-first for HTML, falling back to a cached copy or an offline page. Astro copies public/sw.js to the root of the build, which gives the worker control over the whole site.

Key Takeaways

  • Files in /_astro/ have content hashes in their names, so cache-first is safe for them.
  • HTML changes on every deploy; fetch it from the network first and cache a copy for offline use.
  • Precache a small /offline/ page to show when the network and the cache both miss.
  • Bump the cache version when you change the worker so old caches are deleted.

The service worker

// public/sw.js
const VERSION = 'v1';
const ASSETS = `assets-${VERSION}`;
const PAGES = `pages-${VERSION}`;
const OFFLINE_URL = '/offline/';

self.addEventListener('install', (event) => {
  event.waitUntil(caches.open(PAGES).then((cache) => cache.add(OFFLINE_URL)));
  self.skipWaiting();
});

self.addEventListener('activate', (event) => {
  event.waitUntil(
    caches.keys().then((keys) =>
      Promise.all(keys.filter((k) => ![ASSETS, PAGES].includes(k)).map((k) => caches.delete(k)))
    )
  );
  self.clients.claim();
});

self.addEventListener('fetch', (event) => {
  const { request } = event;
  const url = new URL(request.url);
  if (request.method !== 'GET' || url.origin !== location.origin) return;

  // Hashed build assets: cache first.
  if (url.pathname.startsWith('/_astro/')) {
    event.respondWith(
      caches.match(request).then(
        (hit) =>
          hit ??
          fetch(request).then((res) => {
            const copy = res.clone();
            caches.open(ASSETS).then((cache) => cache.put(request, copy));
            return res;
          })
      )
    );
    return;
  }

  // Pages: network first, then cache, then the offline page.
  if (request.mode === 'navigate') {
    event.respondWith(
      fetch(request)
        .then((res) => {
          const copy = res.clone();
          caches.open(PAGES).then((cache) => cache.put(request, copy));
          return res;
        })
        .catch(async () => (await caches.match(request)) ?? caches.match(OFFLINE_URL))
    );
  }
});

Images in public/, fonts and other requests fall through to the network as normal. Add another branch if you want them cached too.

The offline page and registration

Create src/pages/offline.astro with a short message and links to key pages. It is a normal page, so it uses your layout and styles. Then register the worker from the base layout:

---
// src/components/RegisterSW.astro
---
<script>
  if ('serviceWorker' in navigator && import.meta.env.PROD) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/sw.js');
    });
  }
</script>

The import.meta.env.PROD check keeps the worker out of astro dev, where cached files would get in the way of hot reloading. Test with npm run build && npx astro preview, then in Chrome DevTools open Application, Service workers, and tick Offline to simulate a dropped connection. Our script tag guide explains how Astro bundles this script.

Updating safely

A service worker is the one file on your site you must be careful with, because a broken one keeps serving stale content.

  1. Never cache sw.js itself for long. Serve it with Cache-Control: no-cache. Our cache headers tip shows the _headers rules.
  2. Bump VERSION when you change caching logic. The activate handler deletes caches with other names.
  3. Keep a kill switch. If something goes wrong, deploy a sw.js that calls self.registration.unregister() in activate.

HTML is always tried from the network first, so normal content deploys show up immediately for online visitors without a version bump.

When to use a generated worker instead

For app-like sites that should precache many routes, @vite-pwa/astro generates a Workbox service worker at build time with a precache manifest of your files. For a blog, docs or marketing site, the hand-written worker above is easier to read and debug. Pair either with a web app manifest if you want the site to be installable. The themes in our catalog are static builds, so this worker drops into any of them; the deploy docs cover where dist/ goes next.

FAQ

Where should the service worker file go in Astro?

In public/sw.js. Astro copies it to the site root, and a worker at the root can control every page. A worker in a subfolder only controls pages under that folder.

Does a service worker work with on-demand rendered Astro pages?

Yes. The worker only sees requests and responses. Network-first caching works the same for prerendered and server-rendered HTML, but avoid caching pages that show personal or signed-in data.

Why do I still see old content after deploying?

Usually the HTML is being served cache-first, or sw.js itself is cached by the browser or CDN. Use network-first for navigations and serve sw.js with no-cache.

Does a service worker make my Astro site faster?

For repeat visits, yes: cached assets load from disk with no network request. The first visit is unchanged, so it does not help first-load Core Web Vitals.