A walkthrough of the PWA layer of a real project: precached shell, offline data, an install button, and updates that never interrupt your work.
Let’s say you have built a beautiful web app with React. It looks good on your mobile device, but you feel it could work as an app. The one that I have built here for this example, started as a Vite React web app. It eventually became a kanban board and it looks really good on a mobile device, if I have to say so myself.
A kanban board is the kind of tool people open in awkward places: a lift, a site visit, a train through a tunnel, but if the board shows a white screen the moment the signal drops, people stop trusting it.
So, now it works offline, but still, I need to open my web browser each time. Is there a way to convert it directly so that it looks and feel like your run of the mill mobile app?
I will walk through how I built the offline and install layer of my kanban app (React, Redux Toolkit, Vite, Firebase). It is a closed-team tool, so a few choices, such as wiping cached data on sign-out, are stricter than a public app would need. The code is trimmed from the real project, so, NO, these are not codes about building a kanban board, but it is codes for creating a pure offline capable PWA with React.
What we’ll build:
- An app shell that loads with no network (service worker + Workbox precache).
- Offline data: boards readable offline, edits queued and synced on reconnect (Firestore persistence).
- An honest connection indicator, because navigator.onLine lies.
- An install button (Chromium) and a hint for iOS, which has no install prompt.
- Updates that never reload the page mid-edit, plus a manual Refresh app escape hatch.
- Cache hygiene: big lazy chunks cached on demand, and cached data wiped on sign-out.
The shape of the problem
Offline support is really three separate problems, and mixing them up is the most common source of confusion:
- Code (HTML, JS, CSS, icons)- Cached by: a service worker, stored in Cache Storage
- Data (boards, cards, comments)- Cached by: Firestore’s IndexedDB cache
- Uploads (images, files)- Not cached: they need a connection
The service worker knows nothing about your data, and Firestore knows nothing about your code. Keep them apart in your head and each piece stays small.
Step 1: The manifest and vite-plugin-pwa
We use vite-plugin-pwa with the injectManifest strategy. That means we write our own service worker (src/sw.ts) and the plugin injects the list of files to precache. It is more work than the zero-config generateSW mode, but we need custom routing, so it pays off.
// vite.config.ts
import { VitePWA } from "vite-plugin-pwa";
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: "prompt", // never update behind the user's back
strategies: "injectManifest",
srcDir: "src",
filename: "sw.ts",
injectRegister: false, // we register from React (see Step 5)
manifest: {
name: "TFX Kanban",
short_name: "TFX Kanban",
start_url: "/",
scope: "/",
display: "standalone", //Opens without looking like its on a browser
theme_color: "#e8e4db",
background_color: "#e8e4db",
icons: [
{ src: "/icons/icon-192.png", sizes: "192x192", type: "image/png" },
{ src: "/icons/icon-512.png", sizes: "512x512", type: "image/png" },
{ src: "/icons/icon-maskable-512.png", sizes: "512x512",
type: "image/png", purpose: "maskable" },
],
},
injectManifest: {
globPatterns: ["**/*.{js,css,html,png,woff2,webmanifest}"],
// Large, rarely-needed files are NOT precached (see Step 6).
globIgnores: ["**/assets/sketch-editor/**", "excalidraw/**"],
},
}),
],
});
Three details from the code above that you need to look at here:
- display: “standalone” is what makes the installed app open without browser and makes it feel like an app.
- A maskable icon lets Android crop your icon into whatever shape the launcher uses without cutting off the logo.
- registerType: “prompt” is a product decision, not a technical one. We want the user to decide to install. We’ll come back to it.
Step 2: The service worker
The whole worker is small. Its job is to precache the shell and answer every navigation with it.
// src/sw.ts
/// <reference lib="webworker" />
import { cleanupOutdatedCaches, matchPrecache, precacheAndRoute } from "workbox-precaching";
import { NavigationRoute, registerRoute } from "workbox-routing";
declare const self: ServiceWorkerGlobalScope;
// Vite-plugin-pwa replaces __WB_MANIFEST with the list of built files + hashes.
precacheAndRoute(self.__WB_MANIFEST);
cleanupOutdatedCaches();
// A new worker waits until the page says so, so an update
// never takes over in the middle of an edit.
self.addEventListener("message", (event) => {
if (event.data?.type === "SKIP_WAITING") void self.skipWaiting();
});
// Single-page app: every navigation gets the shell. If even that is
// missing, fall back to a tiny static offline page.
registerRoute(
new NavigationRoute(async () => {
const shell = await matchPrecache("/index.html");
if (shell) return shell;
return (await matchPrecache("/offline.html")) ?? Response.error();
}),
);
Why this works: React Router handles /boards/abc on the client, so the server never has a file for it. By answering every navigation with the cached index.html, deep links work offline too.
offline.html is the last resort: if someone opens the app for the very first time with no connection, there is no shell to serve. A static page with a Try again button is better than the browser’s dinosaur. Keep it free of any JavaScript bundle, because it has to work when nothing else does.
Don’t let your host cache the wrong things
The service worker and the HTML must never be cached by the CDN, or users will be stuck on old versions. Hashed assets, on the other hand, can be cached forever. This project is deployed to Firebase hosting, in firebase.json:
"headers": [
{ "source": "/sw.js", "headers": [{ "key": "Cache-Control", "value": "no-cache" }] },
{ "source": "/index.html", "headers": [{ "key": "Cache-Control", "value": "no-cache" }] },
{ "source": "/offline.html", "headers": [{ "key": "Cache-Control", "value": "no-cache" }] },
{ "source": "/assets/**", "headers": [{ "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }] }
]
This is the single most common cause of “I deployed but nothing changed” with PWAs. In the above firebase.json, assets has been set to immutable, because the expectation is it will not be updated too often.
Step 3: Offline data with Firestore
The shell loads offline, but a board with no cards is useless. Firestore has a built-in persistent cache backed by IndexedDB. It serves previously read documents when offline, and it queues writes and replays them on reconnect.
// src/firebase/firebase.ts
import {
initializeFirestore, getFirestore, memoryLocalCache,
persistentLocalCache, persistentMultipleTabManager,
} from "firebase/firestore";
function createFirestore() {
try {
if (typeof indexedDB === "undefined") throw new Error("no persistent cache");
return initializeFirestore(app, {
localCache: persistentLocalCache({
tabManager: persistentMultipleTabManager(), // several tabs share one cache
}),
});
} catch {
try {
return initializeFirestore(app, { localCache: memoryLocalCache() });
} catch {
return getFirestore(app); // already initialised (hot reload)
}
}
}
export const db = createFirestore();
Notes:
- persistentMultipleTabManager matters. Without it, a second open tab fails to get the IndexedDB lock.
- The fallback to memoryLocalCache keeps the app working in private modes and old browsers where IndexedDB is refused. You lose offline, not the app.
- Your UI code doesn’t change. onSnapshot listeners keep firing with cached data, and writeBatch(…).commit() resolves locally. Only the sync is deferred.
What offline does not cover: uploads
Firestore queues writes silently, but file uploads to Cloud Storage fail loudly when offline. We treat that as a feature. Uploads check connectivity first and say so plainly:
export async function addAttachment(args: {...}) {
if (isOffline()) throw new OfflineError(); // "Adding files needs a connection"
// 1. upload the file
// 2. only then write the record + count in one batch
}Its important to note, order matters here too: upload first, write the record second. A Firestore write succeeds instantly offline, so if you wrote the record first you would show a file that doesn’t exist.
Step 4: An honest connection indicator
navigator.onLineonly says whether the device has a network interface up. A hotel wifi page, a dead VPN or a flaky tunnel all report `true` while nothing works. We combine two signals.
Signal 1: the browser’s events.
const subscribeOnline = (set: (online: boolean) => void) => {
const update = () => set(navigator.onLine);
window.addEventListener("online", update);
window.addEventListener("offline", update);
return () => {
window.removeEventListener("online", update);
window.removeEventListener("offline", update);
};
};Signal 2: ask Firestore. Listen to the signed-in person’s own member document with includeMetadataChanges. If the snapshot keeps coming fromCache, the server is out of reach:
const UNREACHABLE_AFTER_MS = 2500;
stopDoc = onSnapshot(
doc(db, "members", user.email.toLowerCase()),
{ includeMetadataChanges: true },
(snap) => {
if (!snap.metadata.fromCache) {
clearTimeout(timer); timer = undefined;
setUnreachable(false);
} else {
timer ??= setTimeout(() => setUnreachable(true), UNREACHABLE_AFTER_MS);
}
},
);
The timeout avoids flicker: a snapshot is briefly fromCache on every page load before the server answers.
We will also show Syncing changes if writes are pending, using waitForPendingWrites plus a 400 ms delay so normal fast writes never flash a notice. Then one tiny module shares the result with non-React code:
// src/pwa/connectivity.ts
let serverUnreachable = false;
export const setServerUnreachable = (v: boolean) => { serverUnreachable = v; };
export const isOffline = () =>
(typeof navigator !== "undefined" && !navigator.onLine) || serverUnreachable;
The header text is deliberately calm: nothing when online and in sync, Syncing changes while writes drain, and Offline. Changes will sync when you reconnect when offline with edits waiting.
Step 5: Installing the app
Chromium (desktop and Android)
Chromium fires beforeinstallprompt once, early, possibly before React mounts. If you listen inside a component you will miss it. So we capture it in a module that starts listening on import, and expose it through useSyncExternalStore:
// src/pwa/install.ts
import { useSyncExternalStore } from "react";
type PromptEvent = Event & {
prompt: () => Promise<void>;
userChoice: Promise<{ outcome: string }>;
};
type State = { event: PromptEvent | null; installed: boolean };
let state: State = { event: null, installed: isInstalledApp() };
const listeners = new Set<() => void>();
const set = (next: Partial<State>) => {
state = { ...state, ...next };
listeners.forEach((l) => l());
};
window.addEventListener("beforeinstallprompt", (e) => {
e.preventDefault(); // hide the browser's own mini-bar
set({ event: e as PromptEvent });
});
window.addEventListener("appinstalled", () => set({ event: null, installed: true }));
async function install() {
const { event } = state;
if (!event) return;
set({ event: null }); // the event works only once
await event.prompt();
await event.userChoice;
}
export function useInstall() {
const { event, installed } = useSyncExternalStore(
(l) => (listeners.add(l), () => listeners.delete(l)),
() => state,
);
return { canInstall: !!event && !installed, installed, install };
}
Import this file first in main.tsx, so the listener exists before anything else runs. The button then renders only when the browser says installation is possible:
export function InstallButton() {
const { canInstall, install } = useInstall();
if (!canInstall) return null;
return <IconButton label="Install app" icon={Download} onClick={() => void install()} />;
}No dead button, no button after install.
iOS Safari
iOS has no install prompt. The only route is Share, then Add to Home Screen. So we detect iOS Safari and show a dismissible hint once. Detection has one quirk: iPadOS reports itself as a Mac, so touch points tell it apart.
export function isIosSafari(): boolean {
const ua = navigator.userAgent;
const ios = /iPhone|iPad|iPod/.test(ua) ||
(/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);
const otherBrowser = /CriOS|FxiOS|EdgiOS|OPiOS|GSA/.test(ua);
return ios && !otherBrowser && /Safari/.test(ua);
}
export function isInstalledApp(): boolean {
if ((navigator as any).standalone === true) return true; // iOS Home Screen flag
return window.matchMedia?.("(display-mode: standalone)").matches ?? false;
}The dismissal is remembered in localStorage, wrapped in try/catch, because private mode can throw. If it fails, the hint simply returns next visit.
Step 6: Updates that never interrupt an edit
The default PWA behaviour, skipWaiting() plus clients.claim(), swaps in a new service worker immediately. If the new version expects different data or a different chunk layout, a user mid-edit gets a broken page.
We chose the opposite: a new worker installs and waits. The page shows a small notice, and the user decides when to reload.
// src/pwa/UpdatePrompt.tsx
import { useRegisterSW } from "virtual:pwa-register/react";
export function UpdatePrompt() {
const { needRefresh: [needRefresh], updateServiceWorker } = useRegisterSW();
if (!needRefresh) return null;
return (
<div role="status" className="fixed inset-x-4 bottom-4 ...">
<span>Update available</span>
<IconButton label="Reload" icon={RefreshCw} tone="primary"
onClick={() => updateServiceWorker(true)} />
</div>
);
}
Pressing Reload sends the SKIP_WAITING message our worker listens for (Step 2), and the page reloads under the new version.
The escape hatch: Refresh app
Sometimes a user is stuck on an old build and no prompt appears. We added a Refresh app action in Settings. It deletes this site’s caches, unregisters the worker and reloads. Importantly, it does not touch sign-in or Firestore’s offline data, and it warns first if edits are still waiting to sync.
// src/pwa/refresh.ts
export async function hasUnsyncedEdits(waitMs = 500): Promise<boolean> {
let timer: ReturnType<typeof setTimeout> | undefined;
const stillWaiting = new Promise<true>((r) => { timer = setTimeout(() => r(true), waitMs); });
const synced = waitForPendingWrites(db).then(() => false as const, () => false as const);
try { return await Promise.race([synced, stillWaiting]); }
finally { clearTimeout(timer); }
}
export async function refreshApp(): Promise<void> {
if (typeof caches !== "undefined") {
await Promise.all((await caches.keys()).map((name) => caches.delete(name)));
}
const registration = await navigator.serviceWorker?.getRegistration();
await registration?.unregister();
reloadApp();
}
waitForPendingWrites resolves when the server has acknowledged everything. Racing it against a short timer turns it into a yes/no answer: is something still waiting? When online, a write is acknowledged within moments, so a 500 ms wait is enough.
We also bake the short git commit into the build (define: { __APP_VERSION__: … }) and show it in Settings. When someone says it’s still broken, the first question, which version?, has a one-glance answer by referring to the version and usually the las 2 digits are enough to check if the system is unique.
Step 7: Cache hygiene
Two details keep the app light and safe.
Don’t precache the heavy, rarely-used code
The sketch editor that I planned to use in my kanban board (Excalidraw) is large. Precaching it would make installing the app slow for everyone, even people who never draw. So we exclude it from the precache and cache it the first time it is used:
const SKETCH_EDITOR_CACHE = "sketch-editor";
const cacheFirst = (dropOlderHashes: boolean) =>
async ({ request }: { request: Request }) => {
const cache = await caches.open(SKETCH_EDITOR_CACHE);
const hit = await cache.match(request);
if (hit) return hit;
const response = await fetch(request);
if (response.ok) {
if (dropOlderHashes) {
// a new build's chunk replaces the old hash of the same chunk
const name = chunkName(new URL(request.url).pathname);
for (const old of await cache.keys()) {
if (chunkName(new URL(old.url).pathname) === name) await cache.delete(old);
}
}
await cache.put(request, response.clone());
}
return response;
};
registerRoute(({ url }) => url.pathname.startsWith("/assets/sketch-editor/"), cacheFirst(true));
To route by path, we need those chunks to live under a distinct path. Rollup’s chunkFileNames lets us place them under assets/sketch-editor/, so the service worker can tell them apart with a simple `startsWith`. Cache-first is safe because the file names carry a content hash, so a name never changes meaning.
The result: a sketch opened once online opens again offline, and the install stays light.
Wipe cached data on sign-out
Firestore’s IndexedDB cache outlives the session. On a shared device, the next person could see the previous person’s boards offline. So sign-out requests a wipe, and the next load performs it before serving any cached data:
export function startOfflineCache(clear: () => Promise<void>) {
const pending = hasWipeRequest();
const done = pending
? clear().then(() => clearWipeRequest(), () => { /* keep it: retry next load */ })
: Promise.resolve();
return { pending, servePersistent: !pending, done };
}While a wipe is pending, the app uses the in-memory cache instead of the persistent one. The request is only dropped once the delete actually succeeded; if another tab holds the database open, it stays and retries on the next load. The same mechanism applies when a team member is removed: they lose access on reconnect, and their cache is cleared.
Testing it
Offline behaviour is easy to break quietly, so we test at three levels:
- Unit tests for the install state machine, the iOS detection, the update prompt and the cache-wipe logic.
- Emulator tests (Firebase emulators) for rules and data flows.
- Playwright for end-to-end flows, including going offline with context.setOffline(true).
One honest caveat: automated tests tell you the logic is right, but a PWA still needs real devices. You will need to install it on an actual phone, put it in airplane mode, and open it. I recommend doing that before every release that touches the service worker t make sure that everythig works a expected.
Lessons learned
- Separate code caching from data caching. They are different tools solving different problems.
- Make updates the user’s choice. A prompt costs one tap. A broken mid-edit reload costs trust.
- Never trust navigator.onLine alone. Ask the server you actually depend on. Don’t just trust navigtor.onLine to check.
- Capture `beforeinstallprompt` at import time, not in a component.
- Give people an escape hatch. Refresh app plus a visible version number saves hours of support.
- Be explicit about what doesn’t work offline. Saying Adding files needs a connection is kinder than a silent failure.
- Treat the offline cache as sensitive data. Wipe it on sign-out.
Conclusion
None of these pieces is complicated alone. The service worker is only about forty lines. The install logic is about fifty. Offline data is a configuration option. The craft is in how they fit together: an app that opens instantly, tells the truth about its connection, never changes under your hands, and can be installed like any other app on your device.
If you are planning to build something similar, start with the shell and the manifest, get all the installation matters sorted, then add data persistence, and only then polish the edges as you go. At least the PWA part is done.
Selamat Mengaturcara.
Building an Offline-First, Installable Web App with React, Firebase and Workbox was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.






