service worker · pwa · cache · offline · live

Generate a service worker file

Pick a caching strategy — cache-first, network-first, stale-while-revalidate, cache-only or network-only — and get a ready-to-ship sw.js.

Service Worker Template
Strategy
cache-first
policy
Cache
v1
name
Precache URLs
4
items
Bytes
791
code
StrategyCache
input · precache urls
output · service-worker.js
// Cache-first: serve from cache, fall back to network.
const CACHE_NAME = "v1";
const PRECACHE = ["/", "/index.html", "/styles.css", "/app.js"];

self.addEventListener("install", (e) => {
  e.waitUntil(caches.open(CACHE_NAME).then((c) => c.addAll(PRECACHE)));
  self.skipWaiting();
});

self.addEventListener("activate", (e) => {
  e.waitUntil(caches.keys().then((keys) =>
    Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k)))
  ));
  self.clients.claim();
});

self.addEventListener("fetch", (e) => {
  e.respondWith(
    caches.match(e.request).then((cached) =>
      cached || fetch(e.request).then((res) => {
        const clone = res.clone();
        caches.open(CACHE_NAME).then((c) => c.put(e.request, clone));
        return res;
      })
    )
  );
});
Quick Start

How to use a service worker

Service workers intercept fetch requests so your app keeps working offline or runs faster on repeat visits. Register one from your HTML.

  1. 01

    Pick a strategy

    Cache-first for static apps, network-first for fresh data, SWR for the best of both.

    Lookups reference the IANA registries (MIME, HTTP status, TLDs) bundled at build time — no live network calls, no rate limits, no leaked queries.

    strategyIANAregistryofflinelive
    policy · querycache · IANA
    cache · network · swr
    loaded · IANA bundlespec · ready
  2. 02

    Name the cache

    Bumping the cache name forces clients to refresh on the next install.

    Builders emit canonical syntax per the relevant RFC (9110 for HTTP, 5322 for headers, 3986 for URLs) so the output passes spec-compliant parsers.

    cacheRFC 9110canonicalspec-compliantlive
    cache · optionsv1 · live
    v1 → v2
    options applied · livecanonical
  3. 03

    Precache app shell

    List the HTML, CSS, JS bundles the app needs to render offline.

    Validation flags common pitfalls — uppercase header names, smart quotes inside Content-Type, missing ;charset=utf-8 — before they bite production.

    precachevalidationlintpitfallslive
    precache · looked uplist · ready
    / /index.html /app.js
    result · livevalidated
  4. 04

    Register from HTML

    Call navigator.serviceWorker.register("/service-worker.js").

    Copy writes the snippet directly into your clipboard; downloads emit the right extension and MIME so curl/httpie pick them up correctly.

    registerclipboardMIME-correctblobcurl-ready
    ok · copiedready · done
    sw.register()
    shipped · ready to shipsuccess
Pro tips

Web-spec details that bite later

Idempotency saves retries

POST/PUT/DELETE should be safely retried. Use idempotency keys and return the same response on duplicate requests.

Match RFC 9110 status codes

Don’t invent codes. 422 for validation errors, 409 for conflicts, 429 for rate limits. Standard codes work with off-the-shelf clients.

Set <code>Cache-Control</code> deliberately

Default browser caching is conservative. Use max-age + stale-while-revalidate for hot endpoints.

Validate Open Graph in dev

OG tags break silently. Use a previewer like OG Generator + Facebook’s debugger before launch.

CORS is a server concern

The browser sends the preflight; the server decides. Wildcard origins disable credentials — be explicit.

MIME drives behaviour

Servers must send the right Content-Type. Browsers sniff but the spec says they shouldn’t — be explicit to avoid surprises.

Use Cases

When to use a service worker

PWA, offline, speed, asset caching.

PWAs

Make an installable, offline-capable app from your site. Bundled from IANA registries at build time — no live network call, no rate limit, no leaked queries. The MIME, TLD, and status-code tables are baked in so the tool works offline once loaded.

spec-compliant

Offline reading

Cache articles and docs for in-flight reading. Output is canonical per the relevant RFC (9110 for HTTP, 5322 for headers, 3986 for URLs), so spec-compliant parsers accept it as-is. Cross-browser and cross-library behaviour stays consistent.

offline

Snappy repeats

Stale-while-revalidate makes second loads instant. Pairs with the curl-to-fetch converter for end-to-end test stubs — copy the curl from DevTools, paste, get an idiomatic fetch() body. Drop into Playwright/Vitest fixtures without manual translation.

IANA-backed

Bandwidth savings

Stop re-downloading the same assets on every visit. Catches common pitfalls (uppercase header names, smart quotes inside Content-Type, missing ;charset=utf-8) before they bite production. Validation flags rather than auto-corrects so you stay in control.

RFC-aligned

Background sync

Queue actions while offline, replay when reconnected. Validation runs as you type — copy only when the output is shaped correctly. The output drops directly into nginx, Apache, or CDN configs without re-formatting or re-quoting.

production-grade

Reliable kiosks

Run point-of-sale or signage even if WiFi drops. Same input plus same options always produces identical canonical output, so the tool is safe to embed in CI scripts that diff against expected configs.

curl-ready
FAQ

Frequently asked questions

At the root of your site so it can control the whole origin. Place service-worker.js next to index.html.
Service workers require HTTPS (or localhost). It's a security requirement enforced by every browser.
Bump the CACHE_NAME constant. The new SW activates on next page visit, cleaning up old caches.
Inside the fetch handler, branch on the URL or destination to mix strategies — cache-first for assets, network-first for /api/.
Generation is local. The output SW runs in the user's browser; runs locally for them as well.
Suggest a tool

Something missing?

Tell us what you need. We ship the top requests every two weeks.

Sent straight to the maintainers · no account needed
47 in queue·8 shipped this month
Request queued. Thanks!