Advanced PWA: Background Sync, Push, and Offline
A manifest file and an install prompt make a site installable, but they do not make it feel like an app. The moment a user opens your Next.js application on a train, taps a button that should save something, and watches it vanish, the install was not worth it. The advanced layer of a Progressive Web App is about exactly that gap: work that must happen without a network, updates that must arrive while the app is closed, and storage decisions that decide whether any of it is reliable.
This lesson covers the three features teams reach for after the basics â background sync, push notifications, and durable offline storage â plus the debugging workflow that makes service worker bugs tractable.
Prerequisites
- !A working service worker and web app manifest
- !Comfort with async JavaScript and Promises
- !Basic knowledge of HTTP caching
What You'll Learn
- 1Design a cache strategy that does not serve yesterday's JavaScript
- 2Queue failed writes and replay them with Background Sync
- 3Wire a push subscription from browser to server and back
- 4Choose between Cache Storage, IndexedDB, and local storage with a clear rule
Caching that survives your next deploy
The most common advanced-PWA bug is not offline failure, it is stale success: the app comes back from cache running last week's build while the API has moved on, and the mismatch surfaces as a mysterious crash. Fixing it starts with separating what you precache from what you fetch at runtime. Precache the application shell â HTML, hashed JavaScript, hashed CSS â so the app opens without a network. Route everything else deliberately, and never use a cache-first strategy for documents or API responses that can change between deploys.
// public/sw.js â bundled with workbox-cli, @serwist/next, or a similar build step
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
precacheAndRoute(self.__WB_MANIFEST);
cleanupOutdatedCaches();
registerRoute(
({ request }) => request.destination === 'image',
new CacheFirst({
cacheName: 'images-v3',
plugins: [new ExpirationPlugin({ maxEntries: 200, maxAgeSeconds: 60 * 60 * 24 * 30 })],
})
);
registerRoute(
({ url }) => url.pathname.startsWith('/api/feed'),
new NetworkFirst({
cacheName: 'feed-v1',
networkTimeoutSeconds: 3,
})
);
registerRoute(
({ request }) => request.mode === 'navigate',
new StaleWhileRevalidate({ cacheName: 'pages-v1' })
);
Notice the version numbers baked into the cache names. They are crude and effective: when a strategy change breaks something, bumping the version forces every client onto a clean cache on the next visit. Notice also that navigation uses stale-while-revalidate rather than cache-first, so the user gets an immediate response while a fresh document is fetched behind them.
Queuing writes with Background Sync
Reads are the easy half. Writes are where offline support earns its reputation, because a form submission that fails silently is worse than one that never worked. Background Sync lets the service worker register interest in a tag, get woken when connectivity returns, and finish a job the page started â even if the tab is long closed.
// app/offline-queue.js â client-side queue backed by IndexedDB
'use client';
const DB_NAME = 'app-offline';
const STORE = 'pending-writes';
function openDb() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, 1);
request.onupgradeneeded = () => request.result.createObjectStore(STORE, { keyPath: 'id', autoIncrement: true });
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function enqueueWrite(payload) {
const db = await openDb();
await new Promise((resolve, reject) => {
const tx = db.transaction(STORE, 'readwrite');
tx.objectStore(STORE).add({ payload, createdAt: Date.now() });
tx.oncomplete = resolve;
tx.onerror = () => reject(tx.error);
});
const registration = await navigator.serviceWorker.ready;
await registration.sync.register('flush-queue');
}
// service worker side
self.addEventListener('sync', (event) => {
if (event.tag === 'flush-queue') {
event.waitUntil(flushQueue());
}
});
async function flushQueue() {
const db = await openDb();
const records = await new Promise((resolve) => {
const tx = db.transaction(STORE, 'readonly');
const cursor = tx.objectStore(STORE).getAll();
cursor.onsuccess = () => resolve(cursor.result);
});
for (const record of records) {
const response = await fetch('/api/notes', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(record.payload),
});
if (response.status === 409 || response.status === 422) {
await deleteRecord(record.id); // permanently rejected, do not retry forever
continue;
}
if (!response.ok) return; // keep the rest queued, sync will retry
await deleteRecord(record.id);
}
}
The rejection branch is the detail teams forget. A validation failure will fail identically on every retry, so replaying it forever clogs the queue and hides real problems. Drop records the server has permanently refused, keep the ones that failed transiently, and surface the dropped ones in the interface so the user knows their note never arrived.
Push notifications, end to end
Push has four moving parts: permission, a subscription tied to an application server key, a server that stores the subscription, and a background job that sends to it while the app is closed. The browser half is short, but it only works over a secure origin with a service worker that can receive the event.
// client: create a subscription once, send it to your server
'use client';
export async function enablePush() {
const permission = await Notification.requestPermission();
if (permission !== 'granted') return null;
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY),
});
await fetch('/api/push/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription),
});
return subscription;
}
// service worker: show the notification when a push arrives
self.addEventListener('push', (event) => {
const data = event.data ? event.data.json() : { title: 'Update', body: 'New activity' };
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: '/icons/icon-192.png',
data: { url: data.url || '/' },
})
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
event.waitUntil(clients.openWindow(event.notification.data.url));
});
On the server you sign the outgoing message with the private VAPID key and post it to the push service endpoint recorded in the subscription. Two operational rules apply: request permission only after a clear user gesture explaining what they will receive, because browsers now block surprise prompts; and treat the stored subscription as disposable, deleting it when the push service answers with an invalid or gone status so your sender does not keep paying for dead endpoints.
Choosing storage: a decision table
| Store | Synchronous API | Typical ceiling | Survives restart | Use it for |
|---|---|---|---|---|
| Cache Storage | No | Quota-managed | Yes | Shell assets, images, API GET responses |
| IndexedDB | No, Promise-based | Quota-managed | Yes | Queued writes, drafts, structured records |
| Local storage | Yes | About 5 MB | Yes | Tiny flags such as theme or onboarding done |
| Session storage | Yes | About 5 MB | Per tab | Ephemeral UI state that must not leak across tabs |
The rule that keeps teams out of trouble: anything a user created belongs in IndexedDB, anything the network produced belongs in Cache Storage, and local storage is for configuration small enough that losing it costs nothing. Never store tokens or personal data in local storage â it is readable by any script on the page and impossible to partition per tab.
Designing for the moment the signal drops
Offline support that is technically correct still feels broken if the interface does not explain itself. When a request fails, the user needs three pieces of information: that the app noticed, what will happen when connectivity returns, and whether anything they typed is safe. Silent spinners are the worst outcome, because they imply the network is slow rather than absent.
Give queued writes a visible state on the row or card itself â pending, synced, failed â and drive that state from the queue rather than from the request that enqueued it, since that request may never have been attempted. Reads that fall back to cached data should be labelled as cached, with the age of the data where freshness matters, so a stale feed does not silently masquerade as a live one. Prefer optimistic updates that can be rolled back over blocking modals: apply the change immediately, queue it, and reconcile when the sync handler confirms.
Then decide what happens to a write that cannot be reconciled. Surface it in a small persistent list the user can retry or discard, because data that disappears without explanation is the fastest way to lose trust in an offline-first product.
Permissions, quotas, and battery
Background work runs on a platform that is actively trying to protect the device, and the limits are worth knowing before you design around them. Periodic background sync is granted, throttled, and revocable â browsers decide how often it truly runs based on site engagement, so treat it as a hint rather than a schedule. Push permission is effectively one-shot: once denied, most browsers stop surfacing the prompt, so asking at the right moment matters far more than asking early. Notifications themselves cost battery and demand attention, which is why permission prompts that over-promise generate uninstall rates instead of engagement.
Storage and battery quotas apply as well. A worker that wakes constantly, a cache that grows without eviction, and an IndexedDB store that never deletes replayed records all degrade the experience of precisely the users who installed your app. Expiration plugins, queue cleanup, and a small background footprint are not micro-optimisations; they are what keeps the install button honest.
Debugging service workers without hating your life
Service worker bugs are frustrating because the file in your editor and the file running in the browser are frequently different generations of the same idea. In DevTools, the Application panel shows which worker is active, which caches exist, and what is in them. Turn on the update-on-navigation option during development so a reload picks up a new worker, and write a one-line reset routine you can paste into the console to unregister everything and clear every cache â half of all "it works in one window" reports are a stale worker still answering.
Test the offline path deliberately rather than trusting that a cache exists: throttling to offline in the Network panel and reloading proves only that reads are served, not that queued writes replay. Toggle the sync tag by reloading with the network restored and watch the flush happen. Finally, treat the service worker like production code â it is fetched with long-lived caching, so give it a conservative scope, ship changes gradually, and remember that the previous worker keeps controlling open tabs until they are closed.
Common Mistakes
Serving the app shell cache-first so a new deploy never reaches installed clients
Fix: Precache hashed assets, use stale-while-revalidate for navigations, and call the cleanup helper for outdated precaches.
Retrying a permanently rejected write on every sync
Fix: Inspect the response status: drop 4xx records from the queue and keep only transient failures.
Requesting push permission on first paint
Fix: Prompt after a gesture and a plain explanation of what will be sent; blocked permission is close to unrecoverable.
Storing bearer tokens in local storage
Fix: Keep sessions in http-only cookies; local storage is readable by every script on the page.
Naming caches without versions
Fix: Include a version in the cache name so a rollback or strategy change can force a clean slate.
Best Practices
- Separate the precached shell from runtime-cached data and route each deliberately
- Version cache names and clean up outdated ones on activation
- Replay offline writes idempotently so a duplicate retry cannot create two records
- Delete subscriptions the push service reports as gone instead of retrying forever
- Provide a visible pending state for queued writes so the user knows what is unsent
- Verify offline behaviour in DevTools with the worker and cache panels open before shipping
Interview Questions
Q1: Why is cache-first dangerous for navigations in a Next.js app?
The document references hashed bundles that change each deploy, so a cached HTML page can request JavaScript that no longer exists. Stale-while-revalidate gives instant paint while refreshing the document.
Q2: What happens to queued offline writes if the server returns 422?
The record is permanently invalid and will fail every replay, so it should be removed from the queue and surfaced to the user rather than retried indefinitely.
Q3: Which storage would you use for a five-megabyte draft document?
IndexedDB â it is quota-managed, asynchronous, structured, and survives restarts, whereas local storage is synchronous and small.
Q4: How does a closed tab still finish a background sync?
The service worker registered the sync tag, and the browser wakes the worker when connectivity returns, running the handler even though the originating page is gone.
Key Takeaways
- Installability is the floor; advanced PWAs are about surviving a network that disappears.
- Route each request type deliberately and version cache names so deploys cannot strand clients.
- Background Sync replays queued IndexedDB writes, but only transient failures should be retried.
- Push needs permission, a subscription, stored endpoints, and a worker that handles the event.
- Storage has a simple split: user content in IndexedDB, network content in Cache Storage, tiny flags in local storage.
- A console reset routine that unregisters workers and clears caches is the fastest fix for half of service worker bugs.