Progressive Web Apps (PWAs) combine the reach of the web with the experience of native apps. By the end of this guide you’ll have a fully functional PWA that works offline, can be installed on a device’s home screen, and delivers fast, reliable performance—all built with plain JavaScript and a few modern web APIs. This tutorial assumes you’re comfortable with HTML, CSS, and basic JavaScript, but you don’t need any prior experience with service workers or manifests.
What You’ll Need
- A modern browser with DevTools support (Chrome, Edge, or Firefox)
- Node.js (>=14) and npm installed locally
- A code editor (VS Code, Sublime, etc.)
- Basic knowledge of ES6 syntax
- An internet connection to fetch npm packages
Step 1: Scaffold a Simple Web Project
Start by creating a new folder for your project and initializing npm. Open a terminal and run:
mkdir my-pwa
cd my-pwa
npm init -y This creates a package.json file you can later extend. Next, create the core files:
touch index.html main.js style.css Populate index.html with a minimal structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First PWA</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello, Progressive Web App!</h1>
<button id="notifyBtn">Show Notification</button>
http://main.js
</body>
</html> Leave style.css empty for now; you’ll add some basic styling later. This scaffold gives you a static site that we’ll progressively enhance into a PWA.
Step 2: Add a Web App Manifest
The manifest tells browsers how your app should appear when installed. Create a file called manifest.json in the project root and paste the following:
{
"name": "My First PWA",
"short_name": "MyPWA",
"start_url": "/index.html",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#2196f3",
"icons": [
{
"src": "icons/icon-192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "icons/icon-512.png",
"sizes": "512x512",
"type": "image/png"
}
]
} Now link the manifest in index.html inside the <head>:
<link rel="manifest" href="manifest.json"> Don’t forget to add the icons folder and place two PNG files (192 × 192 and 512 × 512). You can generate them with an online tool or use any image editor.
Step 3: Register a Service Worker
Service workers are the backbone of PWAs—they enable caching, push notifications, and background sync. First, create service-worker.js in the root:
// service-worker.js
const CACHE_NAME = 'my-pwa-cache-v1';
const ASSETS_TO_CACHE = [
'/',
'/index.html',
'/style.css',
'/main.js',
'/manifest.json',
'/icons/icon-192.png',
'/icons/icon-512.png'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS_TO_CACHE))
);
});
self.addEventListener('activate', event => {
event.waitUntil(
caches.keys().then(keys => {
return Promise.all(
keys.filter(key => key !== CACHE_NAME).map(key => caches.delete(key))
);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(cachedResponse => {
return cachedResponse || fetch(event.request);
})
);
});
Next, register this worker from main.js:
// main.js
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/service-worker.js')
.then(reg => console.log('Service Worker registered:', reg.scope))
.catch(err => console.error('Service Worker registration failed:', err));
});
}
// Simple notification demo (requires user permission)
const notifyBtn = document.getElementById('notifyBtn');
notifyBtn.addEventListener('click', async () => {
const permission = await Notification.requestPermission();
if (permission === 'granted') {
new Notification('Hello from your PWA!');
}
});
Run a local server (e.g., npx serve . or npm install -g serve && serve .) and open the site in Chrome. Open DevTools → Application → Service Workers to verify registration.
Step 4: Implement Offline‑First Caching Strategies
The naïve cache‑first approach used above works for static assets, but dynamic content often needs a smarter strategy. Replace the fetch listener with a “network‑first, fallback to cache” pattern:
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') return; // ignore non‑GET requests
event.respondWith(
fetch(event.request)
.then(networkResponse => {
// Clone and store in cache for future offline use
const cloned = networkResponse.clone();
caches.open(CACHE_NAME).then(cache => cache.put(event.request, cloned));
return networkResponse;
})
.catch(() => caches.match(event.request))
);
});
This ensures users get the freshest data when online, while still receiving a cached version when offline. Test it by disabling your network in DevTools and refreshing the page—the UI should still load.
Step 5: Enable Add‑to‑Home‑Screen Prompt
Browsers automatically show an install banner when certain criteria are met (HTTPS, manifest, service worker). To give you more control, listen for the beforeinstallprompt event:
let deferredPrompt;
window.addEventListener('beforeinstallprompt', e => {
e.preventDefault(); // Stop automatic prompt
deferredPrompt = e; // Save for later use
const installBtn = document.createElement('button');
installBtn.textContent = 'Install App';
installBtn.style.position = 'fixed';
installBtn.style.bottom = '20px';
installBtn.style.right = '20px';
document.body.appendChild(installBtn);
installBtn.addEventListener('click', async () => {
deferredPrompt.prompt();
const { outcome } = await deferredPrompt.userChoice;
console.log('User response to install prompt:', outcome);
installBtn.remove();
});
});
Now users can tap the custom “Install App” button, and the native install UI will appear. Remember to serve your site over HTTPS (localhost is considered secure for development).
Step 6: Add Push Notifications (Optional Advanced Feature)
Push notifications require a server component, but you can test the client side with the PushManager API and a dummy VAPID key. First, generate a VAPID key pair (use web-push npm package):
npm install -g web-push
web-push generate-vapid-keys Copy the public key and add it to main.js:
const PUBLIC_VAPID_KEY = 'YOUR_PUBLIC_VAPID_KEY_HERE';
async function subscribeUser() {
const registration = await navigator.serviceWorker.ready;
const subscription = await registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(PUBLIC_VAPID_KEY)
});
console.log('Push Subscription:', JSON.stringify(subscription));
// Send subscription to your backend here
}
if ('PushManager' in window) {
const pushBtn = document.createElement('button');
pushBtn.textContent = 'Enable Push';
document.body.appendChild(pushBtn);
pushBtn.addEventListener('click', subscribeUser);
}
function urlBase64ToUint8Array(base64String) {
const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');
const rawData = atob(base64);
return Uint8Array.from([...rawData].map(ch => ch.charCodeAt(0)));
}
When you click “Enable Push,” the browser asks for permission and logs the subscription object. In a production app you’d POST this object to a server that triggers push messages via the Web Push protocol.
Common Mistakes to Avoid
1 Serving over HTTP. PWAs require a secure context. Development on localhost is fine, but any remote testing must use HTTPS.
2 Forgetting to update the cache version. When you change assets, update CACHE_NAME (e.g., my-pwa-cache-v2) so the activate event clears stale files.
3 Over‑caching large responses. Caching API responses without size limits can quickly fill storage. Use Cache-Control headers or set a maximum entry count.
4 Ignoring the manifest.json validation. A malformed manifest prevents the install prompt. Run the Chrome “Manifest” audit to catch errors.
5 Not handling service‑worker updates. Browsers keep the old worker alive until all tabs close. Prompt users to refresh when a new version is detected.
Tips and Tricks
• Use Workbox (npm package workbox-build) to automate cache strategies and generate a service worker with a single command.
• Leverage lighthouse (built into Chrome DevTools) to audit PWA compliance; it will point out missing icons, HTTPS issues, and performance bottlenecks.
• Keep your manifest icons in multiple sizes (including 48 × 48 for Android) to ensure the best visual quality on all devices.
• Test offline behavior with the “Offline” checkbox in the Network tab; this mimics real‑world loss of connectivity.
• Store user preferences (theme, language) in IndexedDB instead of localStorage for larger, structured data.
Frequently Asked Questions
Do I need a backend to build a PWA?
No. A PWA can be a purely static site. However, features like push notifications, authentication, or dynamic content usually require a server or serverless functions.
Can I use a framework like React or Vue?
Absolutely. The steps above are framework‑agnostic, but most modern frameworks provide CLI flags (e.g., create‑react‑app --template cra-template-pwa) that scaffold the manifest and service worker for you.
Why does my app still show “Add to Home screen” on every load?
That usually means the service worker isn’t controlling the page (check the “Service Worker” status in DevTools). Ensure the scope matches your site root and that the file is served from the same origin.
Conclusion
Building a Progressive Web App with JavaScript is a rewarding way to bring native‑like experiences to the open web. By creating a manifest, registering a service worker, implementing smart caching, and handling the install prompt, you’ve turned a static site into an installable, offline‑ready app. From here you can explore advanced capabilities such as background sync, push notifications, and integration with modern front‑end frameworks. Keep iterating, run Lighthouse audits, and watch your PWA climb the performance charts—your users will thank you for the speed and reliability you’ve delivered.
Photo by Portraits of Modern Dairy on Unsplash



