Building installable PWAs with service workers, offline support, and push notifications
# Progressive Web App Development for Google Antigravity
Build installable PWAs with Google Antigravity's Gemini 3 engine. This guide covers service workers, offline caching, push notifications, and app manifest configuration.
## Web App Manifest
```json
// public/manifest.json
{
"name": "My PWA Application",
"short_name": "MyPWA",
"description": "A production-ready Progressive Web App",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#0066cc",
"orientation": "portrait-primary",
"icons": [
{
"src": "/icons/icon-72x72.png",
"sizes": "72x72",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable any"
},
{
"src": "/icons/icon-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable any"
}
],
"screenshots": [
{
"src": "/screenshots/desktop.png",
"sizes": "1280x720",
"type": "image/png",
"form_factor": "wide"
},
{
"src": "/screenshots/mobile.png",
"sizes": "750x1334",
"type": "image/png",
"form_factor": "narrow"
}
],
"categories": ["productivity", "utilities"],
"shortcuts": [
{
"name": "New Document",
"short_name": "New",
"url": "/new",
"icons": [{ "src": "/icons/new.png", "sizes": "96x96" }]
}
],
"share_target": {
"action": "/share",
"method": "POST",
"enctype": "multipart/form-data",
"params": {
"title": "title",
"text": "text",
"url": "url",
"files": [
{
"name": "files",
"accept": ["image/*", "text/*"]
}
]
}
}
}
```
## Service Worker with Workbox
```typescript
// src/sw.ts
import { precacheAndRoute, cleanupOutdatedCaches } from 'workbox-precaching';
import { registerRoute, NavigationRoute, Route } from 'workbox-routing';
import {
NetworkFirst,
CacheFirst,
StaleWhileRevalidate,
} from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';
import { BackgroundSyncPlugin } from 'workbox-background-sync';
declare const self: ServiceWorkerGlobalScope;
// Precache static assets
precacheAndRoute(self.__WB_MANIFEST);
cleanupOutdatedCaches();
// Navigation requests - Network First
registerRoute(
new NavigationRoute(
new NetworkFirst({
cacheName: 'pages',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
],
}),
{
denylist: [/^\/api\//],
}
)
);
// API requests - Network First with timeout
registerRoute(
({ url }) => url.pathname.startsWith('/api/'),
new NetworkFirst({
cacheName: 'api-cache',
networkTimeoutSeconds: 10,
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
new ExpirationPlugin({
maxEntries: 100,
maxAgeSeconds: 60 * 60, // 1 hour
}),
],
})
);
// Images - Cache First
registerRoute(
({ request }) => request.destination === 'image',
new CacheFirst({
cacheName: 'images',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
new ExpirationPlugin({
maxEntries: 100,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
}),
],
})
);
// Static assets - Stale While Revalidate
registerRoute(
({ request }) =>
request.destination === 'script' ||
request.destination === 'style' ||
request.destination === 'font',
new StaleWhileRevalidate({
cacheName: 'static-assets',
plugins: [
new CacheableResponsePlugin({ statuses: [200] }),
],
})
);
// Background sync for failed requests
const bgSyncPlugin = new BackgroundSyncPlugin('api-queue', {
maxRetentionTime: 24 * 60, // 24 hours
});
registerRoute(
({ url }) => url.pathname.startsWith('/api/sync/'),
new NetworkFirst({
plugins: [bgSyncPlugin],
}),
'POST'
);
// Push notifications
self.addEventListener('push', (event) => {
const data = event.data?.json() ?? {};
const options: NotificationOptions = {
body: data.body || 'New notification',
icon: '/icons/icon-192x192.png',
badge: '/icons/badge-72x72.png',
vibrate: [100, 50, 100],
data: {
url: data.url || '/',
},
actions: data.actions || [],
};
event.waitUntil(
self.registration.showNotification(data.title || 'Notification', options)
);
});
self.addEventListener('notificationclick', (event) => {
event.notification.close();
const url = event.notification.data?.url || '/';
event.waitUntil(
self.clients.matchAll({ type: 'window' }).then((clients) => {
for (const client of clients) {
if (client.url === url && 'focus' in client) {
return client.focus();
}
}
return self.clients.openWindow(url);
})
);
});
```
## PWA Registration Hook
```typescript
// hooks/usePWA.ts
import { useState, useEffect, useCallback } from 'react';
interface PWAState {
isInstalled: boolean;
isInstallable: boolean;
isOffline: boolean;
hasUpdate: boolean;
registration: ServiceWorkerRegistration | null;
}
export function usePWA() {
const [state, setState] = useState<PWAState>({
isInstalled: false,
isInstallable: false,
isOffline: !navigator.onLine,
hasUpdate: false,
registration: null,
});
const [deferredPrompt, setDeferredPrompt] = useState<any>(null);
useEffect(() => {
// Check if installed
const isInstalled = window.matchMedia('(display-mode: standalone)').matches;
setState((prev) => ({ ...prev, isInstalled }));
// Listen for install prompt
const handleBeforeInstallPrompt = (e: Event) => {
e.preventDefault();
setDeferredPrompt(e);
setState((prev) => ({ ...prev, isInstallable: true }));
};
// Listen for online/offline
const handleOnline = () => setState((prev) => ({ ...prev, isOffline: false }));
const handleOffline = () => setState((prev) => ({ ...prev, isOffline: true }));
window.addEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
// Register service worker
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js').then((registration) => {
setState((prev) => ({ ...prev, registration }));
registration.addEventListener('updatefound', () => {
const newWorker = registration.installing;
newWorker?.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
setState((prev) => ({ ...prev, hasUpdate: true }));
}
});
});
});
}
return () => {
window.removeEventListener('beforeinstallprompt', handleBeforeInstallPrompt);
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
const install = useCallback(async () => {
if (!deferredPrompt) return false;
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
setDeferredPrompt(null);
setState((prev) => ({ ...prev, isInstallable: false }));
return outcome === 'accepted';
}, [deferredPrompt]);
const update = useCallback(() => {
if (state.registration?.waiting) {
state.registration.waiting.postMessage({ type: 'SKIP_WAITING' });
window.location.reload();
}
}, [state.registration]);
return { ...state, install, update };
}
```
## Push Notification Service
```typescript
// services/push.ts
const VAPID_PUBLIC_KEY = process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!;
export async function subscribeToPush(): Promise<PushSubscription | null> {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
return null;
}
const registration = await navigator.serviceWorker.ready;
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
return null;
}
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(VAPID_PUBLIC_KEY),
});
// Send subscription to backend
await fetch('/api/push/subscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription),
});
return subscription;
}
function urlBase64ToUint8Array(base64String: string): Uint8Array {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = window.atob(base64);
return Uint8Array.from([...rawData].map((char) => char.charCodeAt(0)));
}
```
## Best Practices
Google Antigravity's Gemini 3 engine recommends these PWA patterns: Use Workbox for service worker management. Implement proper caching strategies per resource type. Add background sync for offline actions. Request push notification permission at appropriate times. Test thoroughly with Lighthouse PWA audits.This PWA prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their pwa implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For PWA projects, consider mentioning your framework version, coding style, and any specific libraries you're using.