PWA
A Progressive Web App is a website that behaves like a native app — installable on the homescreen, functional offline, and capable of push notifications. The architecture is deceptively simple: a service worker intercepts network requests, a web app manifest declares app metadata, and IndexedDB provides persistent client-side storage. The challenge is orchestrating these pieces into a coherent offline-first experience.
Imagine opening Twitter on a subway. The train enters a tunnel and you lose signal. The timeline you were scrolling a second ago is now a blank error page. This is the default web experience — the web assumes you are online.
A Progressive Web App flips that assumption. It starts loading fast from a service worker cache, works offline by serving previously cached content, sends push notifications even when the browser is closed, and installs to the homescreen like a native app. Twitter's PWA (Twitter Lite) was 600 KB vs the 23 MB native app and delivered a comparable user experience.
Here is the core setup — the three pillars of a PWA working together:
Three lines of setup code unlock the entire PWA ecosystem. The manifest.json tells the browser what your app looks like when installed. The service worker controls the network. The offline-first architecture handles the rest. Let's walk through how I arrived at this design.
Before writing a single line of service worker code, clarify what the PWA must and must not do. Here are the questions I would ask in a system design interview, and the answers that drive the architecture.
beforeinstallprompt event for a custom install button.push event.The central architectural question for a PWA is: where does the service worker fit in the request flow? The service worker is a programmable proxy that sits between the browser and the network. Every HTTP request from your page passes through it — unless it chooses to bypass.
I settled on a layered architecture with four tiers. At the top is the UI layer (React components). Below it is the Service Worker, which intercepts fetch events and applies cache strategies. The Client-side storage layer (IndexedDB) holds offline data. The Network layer handles background sync and push subscriptions.
A service worker that serves only from cache and never hits the network. Simple and fast, but the user never gets fresh content until the next SW update. Rejected because stale content is unacceptable for dynamic apps like social feeds or dashboards.
A service worker that always passes through to the network. This defeats the purpose of a PWA — no offline support, no performance benefit. Only useful for non-critical apps that must always show the latest data.
A service worker that applies a per-resource strategy: Cache-First for static assets (JS, CSS, images), Network-First for critical API calls, and Stale-While-Revalidate for content that needs freshness but can tolerate a brief stale display. This is the strategy used by Twitter Lite, Pinterest, and Starbucks' PWA.
A PWA's data model spans three storage layers, each with a different purpose and access pattern.
The Cache Storage API holds HTTP responses keyed by Request object. This is the service worker's primary storage — it stores the response streams for HTML, JS, CSS, and images. The cache is opaque to JavaScript code on the main thread; only the service worker reads from it.
IndexedDB holds application data — user preferences, drafts, sync queue, and cached API response payloads (the JSON, not the HTTP response). It is accessible from both the main thread and the service worker, making it the bridge for offline-to-online sync.
Ephemeral state — the current user, active route, Redux store, form drafts — lives in main-thread memory and is not persisted across page loads. Only explicitly-requested persistence (e.g., "Save for offline") writes to IndexedDB.
localStorage as the offline data layer. This works for simple key-value data, but localStorage is synchronous and cannot be accessed from the service worker. IndexedDB is asynchronous and available in both contexts.The PWA does not expose a single component API. Instead, the contract is distributed across three interfaces: the Web App Manifest (tells the browser about the app), the Service Worker API (the event-driven interface), and the client-side storage wrapper.
The manifest is a JSON file that describes your app to the browser. It controls how the app appears on the homescreen (name, icon, theme color) and how it behaves when launched in standalone mode.
The service worker is registered from the main thread and then communicates via events. The registration is a one-liner, but the surrounding setup warrants a dedicated module:
The beforeinstallprompt event fires automatically when the browser determines the app is installable. The app intercepts it, stores the event, and calls prompt() in response to a user gesture (button click).
Let's examine the critical subsystems: service worker cache strategies, the push notification pipeline, offline data storage, and background sync.
A single service worker can apply different cache strategies to different resources. The decision is made inside the fetch event handler based on the request URL, method, and headers.
Cache-First is the simplest and fastest strategy. Check the cache. Hit? Return immediately. Miss? Fetch from network, cache the response, return it. This is ideal for static assets that rarely change:
Stale-While-Revalidate is the most versatile strategy for content that changes but where speed matters more than freshness. Return the cached version immediately, then fetch fresh data in the background and update the cache for next time.
Push notifications require four parties: the browser's Push Service, the service worker, the app server, and the user. The flow is asymmetric — the app server cannot push directly to the browser; it must go through the Push Service.
IndexedDB is the offline storage backend. Unlike the Cache Storage API (which stores HTTP responses), IndexedDB stores structured JSON data that the main thread can query with indexes, cursors, and ranges.
The Sync API allows the service worker to defer actions until the user has connectivity. The main thread registers a sync event tag; the service worker handles it when the browser detects a stable connection.
online / offline events) that manually flushes the sync queue. Always feature-check before registering a sync.Let's trace what happens at the browser engine level when a PWA handles a request offline. I'll walk through the call stack the way Dmitry (@jser.dev) would — focusing on the internal promises, event dispatch order, and microtask timing.
The browser waits 5 seconds for the service worker to call event.respondWith(). If the timeout expires, the browser falls back to the network — which will also fail since the user is offline, resulting in a browser error page. This is why the cache lookup must be fast. If your cache contains hundreds of entries, a naive linear search could push past the 5-second window on a slow device.
The solution is to scope cache lookups: maintain a Set<string> of known cached URLs in the SW's global scope, so a cache miss is O(1) before even touching the Cache Storage API.
Let's trace three complete interactions to see how data flows through the PWA system.
PWA performance is largely about cache strategy selection and storage management. Here are the optimizations I consider essential.
Navigation preload allows the service worker to initiate a network fetch in parallel with SW startup. Without it, a new SW thread must boot before any network request can begin — adding ~100ms to the first navigation.
The Cache Storage API and IndexedDB share a storage quota managed by the browser. On mobile devices, the quota is typically 50-200 MB. The app should self-limit and provide a "Clear cache" option.
navigator.storage.estimate() to show the user how much storage the PWA consumes.navigator.storage.persist() to request persistent storage (the browser will not evict your data without user confirmation).static-v2, content-v2. On SW activation, delete all caches that do not match the current version.Register the service worker on load event, not on page parse. This ensures the initial page load is not delayed by SW registration overhead:
| Strategy | Use case | Offline support | Freshness |
|---|---|---|---|
| Cache First | Static assets (JS, CSS, images) | ✅ Full | Updates only on SW install |
| Network First | Critical API calls, real-time data | ⚠️ Fallback only | ✅ Always fresh |
| Stale-While-Revalidate | Content pages, news feed | ✅ Full | ✅ Stale → fresh in background |
| Network Only | Non-critical analytics | ❌ None | ✅ Always fresh |
PWAs operate with elevated privileges — they intercept network traffic, store data persistently, and display notifications. This surface area demands careful security analysis.
/ if the SW only needs to handle/app/.sw.js, every existing user gets the new SW on their next page load. Use Subresource Integrity (SRI) for the SW script tag, and serve the SW from a separate, hardened endpoint with its own CDN cache policy.Testing a PWA is harder than testing a standard web app because the service worker runs in a separate thread and intercepts network requests. I use three testing tiers.
Test cache strategy functions in isolation by stubbing the caches global and fetch:
Use Puppeteer or Playwright to test the full PWA flow in a headless browser. Enable service workers, toggle network conditions, and assert on cache contents:
Run Lighthouse as part of the CI pipeline to catch regressions in PWA audit scores. The Lighthouse PWA audit checks installability, service worker registration, offline behavior, and manifest correctness.
The specific test cases I consider essential:
PWA accessibility has two dimensions: standard web accessibility inside the app, and the accessibility of the PWA-specific features (install prompt, push notifications, offline banner).
The install button must have an accessible label. Use aria-label since the icon-only button has no visible text. The button should announce "Install app" to screen readers.
When the app detects it is offline, show a non-intrusive banner with role="status" and aria-live="polite" so screen readers announce the state change:
Push notifications are inherently accessible — the operating system delivers them to the notification center, which screen readers (VoiceOver, TalkBack, NVDA) read aloud. However, the notification must include:
vibrate: [200, 100, 200].When the PWA runs in standalone mode (display: "standalone"), there is no browser chrome — no URL bar, no back button, no tab strip. The app must provide its own navigation controls. This includes:
prefers-reduced-motion. If the app uses animated page transitions (common in PWAs), disable them when the user prefers reduced motion.status, alert, button) and descriptive labels. The key principle: the user must understand what state the app is in (online vs offline) and what actions are available (install, retry sync).Try the full PWA implementation in a WebContainer playground below. The demo includes service worker registration, cache strategies, an install prompt handler, and an IndexedDB-based offline task list.
Try these interactions: load the app online, note the service worker registration in the console, then toggle DevTools to offline mode and reload. The app should render from cache. Add a task while offline and watch it sync when you come back online.
localhost.beforeinstallprompt event is the browser's signal that these criteria are met.context.setOffline().A PWA is not a single technology — it is a collection of browser APIs (Service Worker, Cache Storage, IndexedDB, Push API, Sync API, Manifest) that compose into an experience that competes with native apps. The architecture we just designed hits the key requirements: offline-capable, installable, notification-enabled, and background-synced — and the core service worker logic fits in under 50 lines. That is the signature of a well-designed platform: simple primitives that combine to create rich, reliable user experiences.