Builds Progressive Web Apps with React and Vite. Covers manifest configuration, service workers, offline support, installability, and push notifications.
How this skill is triggered — by the user, by Claude, or both
Slash command
/jwynia-agent-skills-1:react-pwaThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
Build Progressive Web Apps with React and Vite using vite-plugin-pwa. This skill covers the complete PWA lifecycle: manifest configuration, service worker strategies, offline support, installability, and push notifications.
Build Progressive Web Apps with React and Vite using vite-plugin-pwa. This skill covers the complete PWA lifecycle: manifest configuration, service worker strategies, offline support, installability, and push notifications.
Use when:
Don't use when:
npm install -D vite-plugin-pwa workbox-window
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.ico', 'apple-touch-icon.png', 'mask-icon.svg'],
manifest: {
name: 'My React PWA',
short_name: 'ReactPWA',
description: 'A Progressive Web App built with React',
theme_color: '#ffffff',
background_color: '#ffffff',
display: 'standalone',
icons: [
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }
]
}
})
]
})
deno run --allow-read --allow-write scripts/generate-icons.ts --input logo.png --output public/
// src/components/PWAUpdatePrompt.tsx
import { useRegisterSW } from 'virtual:pwa-register/react'
export function PWAUpdatePrompt() {
const {
needRefresh: [needRefresh, setNeedRefresh],
updateServiceWorker
} = useRegisterSW()
if (!needRefresh) return null
return (
<div className="pwa-toast">
<span>New content available!</span>
<button onClick={() => updateServiceWorker(true)}>Reload</button>
<button onClick={() => setNeedRefresh(false)}>Close</button>
</div>
)
}
npm create vite@latest my-pwa -- --template react-ts
cd my-pwa
npm install
npm install -D vite-plugin-pwa workbox-window
npm install -D vite-plugin-pwa workbox-window
Add TypeScript types for virtual modules:
// src/vite-env.d.ts (add to existing file)
/// <reference types="vite-plugin-pwa/client" />
The web app manifest defines how the PWA appears when installed.
{
"name": "Full Application Name",
"short_name": "ShortName",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#3b82f6",
"icons": []
}
| Mode | Description | Use Case |
|---|---|---|
fullscreen | No browser UI, fills entire screen | Games, immersive experiences |
standalone | App-like, with system UI only | Most PWAs |
minimal-ui | Minimal browser controls | Apps needing navigation |
browser | Standard browser tab | Fallback only |
deno run --allow-read --allow-write scripts/generate-manifest.ts \
--name "My App" \
--short-name "App" \
--theme "#3b82f6" \
--output public/manifest.webmanifest
vite-plugin-pwa uses Workbox under the hood. Choose a strategy based on your needs.
| Strategy | Behavior | Best For |
|---|---|---|
generateSW | Auto-generates SW from config | Most projects |
injectManifest | Injects precache into custom SW | Custom caching logic |
CacheFirst - Serve from cache, fall back to network:
runtimeCaching: [
{
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-cache',
expiration: { maxEntries: 10, maxAgeSeconds: 60 * 60 * 24 * 365 }
}
}
]
NetworkFirst - Try network, fall back to cache:
{
urlPattern: /^https:\/\/api\.example\.com\/.*/i,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
expiration: { maxEntries: 50, maxAgeSeconds: 60 * 60 * 24 }
}
}
StaleWhileRevalidate - Serve cache immediately, update in background:
{
urlPattern: /\.(?:png|jpg|jpeg|svg|gif)$/,
handler: 'StaleWhileRevalidate',
options: {
cacheName: 'images-cache',
expiration: { maxEntries: 100, maxAgeSeconds: 60 * 60 * 24 * 30 }
}
}
// vite.config.ts
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import { VitePWA } from 'vite-plugin-pwa'
export default defineConfig({
plugins: [
react(),
VitePWA({
registerType: 'autoUpdate',
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
runtimeCaching: [
{
urlPattern: /^https:\/\/api\..*/i,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
expiration: { maxEntries: 100, maxAgeSeconds: 60 * 60 * 24 }
}
},
{
urlPattern: /\.(?:png|jpg|jpeg|svg|gif|webp)$/,
handler: 'CacheFirst',
options: {
cacheName: 'images',
expiration: { maxEntries: 100, maxAgeSeconds: 60 * 60 * 24 * 30 }
}
}
]
},
manifest: {
name: 'My React PWA',
short_name: 'ReactPWA',
theme_color: '#3b82f6',
background_color: '#ffffff',
display: 'standalone',
icons: [
{ src: 'pwa-192x192.png', sizes: '192x192', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png' },
{ src: 'pwa-512x512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }
]
}
})
]
})
Create an offline page that displays when network and cache both fail:
// vite.config.ts - add to VitePWA options
workbox: {
navigateFallback: '/offline.html',
navigateFallbackDenylist: [/^\/api/]
}
Create public/offline.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Offline</title>
<style>
body { font-family: system-ui; display: flex; align-items: center;
justify-content: center; min-height: 100vh; margin: 0; }
.offline { text-align: center; }
</style>
</head>
<body>
<div class="offline">
<h1>You're offline</h1>
<p>Please check your internet connection and try again.</p>
<button onclick="window.location.reload()">Retry</button>
</div>
</body>
</html>
// src/hooks/useOnlineStatus.ts
import { useSyncExternalStore } from 'react'
function subscribe(callback: () => void) {
window.addEventListener('online', callback)
window.addEventListener('offline', callback)
return () => {
window.removeEventListener('online', callback)
window.removeEventListener('offline', callback)
}
}
export function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true // SSR fallback
)
}
Usage:
function App() {
const isOnline = useOnlineStatus()
return (
<div>
{!isOnline && <Banner>You are offline. Some features may be limited.</Banner>}
{/* ... */}
</div>
)
}
// src/components/InstallButton.tsx
import { useState, useEffect } from 'react'
interface BeforeInstallPromptEvent extends Event {
prompt: () => Promise<void>
userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>
}
export function InstallButton() {
const [deferredPrompt, setDeferredPrompt] = useState<BeforeInstallPromptEvent | null>(null)
const [isInstalled, setIsInstalled] = useState(false)
useEffect(() => {
// Check if already installed
if (window.matchMedia('(display-mode: standalone)').matches) {
setIsInstalled(true)
return
}
const handler = (e: Event) => {
e.preventDefault()
setDeferredPrompt(e as BeforeInstallPromptEvent)
}
window.addEventListener('beforeinstallprompt', handler)
window.addEventListener('appinstalled', () => setIsInstalled(true))
return () => window.removeEventListener('beforeinstallprompt', handler)
}, [])
const handleInstall = async () => {
if (!deferredPrompt) return
deferredPrompt.prompt()
const { outcome } = await deferredPrompt.userChoice
if (outcome === 'accepted') {
setDeferredPrompt(null)
}
}
if (isInstalled || !deferredPrompt) return null
return (
<button onClick={handleInstall} className="install-btn">
Install App
</button>
)
}
async function requestNotificationPermission(): Promise<boolean> {
if (!('Notification' in window)) {
console.warn('Notifications not supported')
return false
}
if (Notification.permission === 'granted') return true
if (Notification.permission === 'denied') return false
const permission = await Notification.requestPermission()
return permission === 'granted'
}
async function subscribeToPush(vapidPublicKey: string): Promise<PushSubscription | null> {
const registration = await navigator.serviceWorker.ready
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(vapidPublicKey)
})
// Send subscription to your 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)))
}
// src/sw.ts
import { precacheAndRoute } from 'workbox-precaching'
declare const self: ServiceWorkerGlobalScope
precacheAndRoute(self.__WB_MANIFEST)
self.addEventListener('push', (event) => {
const data = event.data?.json() ?? { title: 'Notification', body: 'New update available' }
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: '/pwa-192x192.png',
badge: '/badge-72x72.png'
})
)
})
self.addEventListener('notificationclick', (event) => {
event.notification.close()
event.waitUntil(
self.clients.openWindow('/')
)
})
Scenario: Convert a Vite React app to an installable PWA with offline support.
Steps:
npm install -D vite-plugin-pwanpm run build && npm run previewVerification:
Scenario: E-commerce app with product API calls that should work offline after browsing.
VitePWA({
workbox: {
runtimeCaching: [
// Cache product images aggressively
{
urlPattern: /\/products\/images\/.*/,
handler: 'CacheFirst',
options: {
cacheName: 'product-images',
expiration: { maxEntries: 200, maxAgeSeconds: 60 * 60 * 24 * 7 }
}
},
// Cache API responses with network-first
{
urlPattern: /\/api\/products\/.*/,
handler: 'NetworkFirst',
options: {
cacheName: 'product-api',
expiration: { maxEntries: 100, maxAgeSeconds: 60 * 60 },
networkTimeoutSeconds: 3
}
}
]
}
})
Scenario: News app that syncs content in background.
// Register periodic sync
const registration = await navigator.serviceWorker.ready
await registration.periodicSync.register('sync-articles', {
minInterval: 60 * 60 * 1000 // 1 hour
})
// Handle in service worker
self.addEventListener('periodicsync', (event) => {
if (event.tag === 'sync-articles') {
event.waitUntil(syncArticles())
}
})
| Script | Purpose | Permissions |
|---|---|---|
generate-manifest.ts | Create manifest.webmanifest | --allow-read --allow-write |
generate-icons.ts | Generate icon set from source | --allow-read --allow-write --allow-run |
generate-sw-config.ts | Create service worker config | --allow-read --allow-write |
audit-pwa.ts | Validate PWA compliance | --allow-read --allow-net |
deno run --allow-read --allow-write scripts/generate-manifest.ts \
--name "My Application" \
--short-name "MyApp" \
--description "A great PWA" \
--theme "#3b82f6" \
--background "#ffffff" \
--display standalone \
--output public/manifest.webmanifest
deno run --allow-read --allow-write --allow-run scripts/generate-icons.ts \
--input logo.svg \
--output public/ \
--sizes 192,512 \
--maskable
deno run --allow-read --allow-net scripts/audit-pwa.ts \
--url http://localhost:5173 \
--format summary
Symptoms: Old content served after deployment.
Solution:
registerType: 'autoUpdate' is setSymptoms: No install prompt, Lighthouse fails installability.
Solution:
Symptoms: Users see outdated data.
Solution:
NetworkFirst strategy for dynamic API endpointsnetworkTimeoutSeconds for faster fallbackSymptoms: Subscription succeeds but notifications don't arrive.
Solution:
userVisibleOnly: true in subscriptionreferences/caching-strategies.md - Deep dive into Workbox caching patternsreferences/push-notifications.md - Complete push notification backend setupreferences/testing-pwas.md - Testing strategies for PWA featuresassets/manifest-template.json - Complete manifest with all optional fieldsassets/sw-template.ts - Custom service worker template for injectManifestnpx claudepluginhub jwynia/agent-skillsBuilds Progressive Web Apps: service workers, caching strategies, offline support, Workbox, and web app manifests. Useful when adding installability and offline reliability.
Guides building Progressive Web Apps with service workers, web app manifests, and offline caching strategies.
Implement Progressive Web App features including service workers, caching strategies, offline support, and installation prompts for React and Svelte applications.