Express.js and Progressive Web Apps
Progressive Web Apps (PWAs) combine the best of web and mobile applications, offering offline capabilities, push notifications, and more. This guide covers key concepts, examples, and best practices for building PWAs with Express.js.
Key Concepts of Progressive Web Apps
- Service Workers: Scripts that run in the background and provide offline capabilities, caching, and background synchronization.
- Web App Manifest: A JSON file that defines the appearance and behavior of the PWA when installed on a user's device.
- HTTPS: Required for PWAs to ensure secure communication between the server and client.
- Responsive Design: Ensuring the app works on a variety of devices and screen sizes.
- Push Notifications: Allowing the app to send notifications to the user even when the app is not actively used.
Setting Up the Project
Initialize a new Express.js project and install necessary dependencies:
// Initialize a new project
// npm init -y
// Install Express
// npm install express
// Create the project structure
// mkdir public
// touch server.js public/index.html public/manifest.json public/service-worker.js
Creating the Web App Manifest
The web app manifest defines the appearance and behavior of the PWA when installed on a user's device:
Example: manifest.json
// public/manifest.json
{
"name": "My PWA",
"short_name": "PWA",
"start_url": "/",
"display": "standalone",
"background_color": "#ffffff",
"theme_color": "#000000",
"icons": [
{
"src": "/images/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/images/icon-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
Creating the Service Worker
Service workers provide offline capabilities, caching, and background synchronization:
Example: service-worker.js
// public/service-worker.js
const CACHE_NAME = 'my-pwa-cache-v1';
const urlsToCache = [
'/',
'/styles.css',
'/script.js',
'/images/icon-192x192.png',
'/images/icon-512x512.png'
];
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request);
})
);
});
Creating the HTML and Serving the Manifest
Create the main HTML file and serve the manifest and service worker:
Example: index.html
// public/index.html
My PWA
Welcome to My PWA