Service Worker is a script that runs in the browser background thread and intercepts network requests. PWA (Progressive Web App) is a web application that works like a native app (offline, push notifications, desktop installation).
Why it matters: PWAs bridge the gap between web and native apps. Companies like Twitter, Pinterest, and Starbucks use PWAs to reach users on slow networks or low-storage devices without requiring app store downloads. A well-configured PWA can load instantly on repeat visits and work fully offline.
What Service Worker provides:
How a Service Worker lifecycle works:
Setup in React (Create React App):
1npm install -D workbox-webpack-plugin
1// src/service-worker.js2import { precacheAndRoute } from "workbox-precaching";3import { registerRoute } from "workbox-routing";4import { StaleWhileRevalidate, CacheFirst } from "workbox-strategies";56// Cache built files7precacheAndRoute(self.__WB_MANIFEST);89// Cache API requests10registerRoute(11 ({ url }) => url.pathname.startsWith("/api/"),12 new StaleWhileRevalidate({ cacheName: "api-cache" })13);1415// Cache images16registerRoute(17 ({ request }) => request.destination === "image",18 new CacheFirst({ cacheName: "images" })19);
Manifest (manifest.json):
1{2 "name": "My App",3 "short_name": "App",4 "start_url": "/",5 "display": "standalone",6 "background_color": "#ffffff",7 "theme_color": "#000000",8 "icons": [9 { "src": "/icon-192.png", "sizes": "192x192", "type": "image/png" },10 { "src": "/icon-512.png", "sizes": "512x512", "type": "image/png" }11 ]12}
Common pitfalls:
Check: Chrome DevTools → Application → Service Workers.