Advanced PWA
Background sync, push notifications, offline storage, and app shortcuts.
Overview
Advanced PWA features provide native app-like experiences.
Key Concepts
- Background Sync — Sync data when online
- Push Notifications — Re-engage users
- Offline Storage — Store data locally
- App Shortcuts — Quick actions from home screen
- Periodic Sync — Background updates
Code Examples
// public/sw.js
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst } from 'workbox-strategies';
precacheAndRoute(self.__WB_MANIFEST);
// Cache images
registerRoute(
({ request }) => request.destination === 'image',
new CacheFirst({ cacheName: 'images', plugins: [
new ExpirationPlugin({ maxEntries: 50 })
]})
);
// Network first for API
registerRoute(
({ url }) => url.pathname.startsWith('/api'),
new NetworkFirst({ cacheName: 'api', networkTimeoutSeconds: 3 })
);
// Background sync
self.addEventListener('sync', (event) => {
if (event.tag === 'sync-data') {
event.waitUntil(syncData());
}
});
// Push notifications
self.addEventListener('push', (event) => {
const { title, body, icon } = event.data.json();
event.waitUntil(
self.registration.showNotification(title, { body, icon })
);
});
// Push notification subscription
'use client';
async function subscribeToNotifications() {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: process.env.NEXT_PUBLIC_VAPID_KEY
});
await fetch('/api/subscribe', {
method: 'POST',
body: JSON.stringify(subscription)
});
}
Practice
Implement background sync and push notifications for a PWA.