=====================================================
Imagine a world where your users receive timely updates and alerts from your Progressive Web App (PWA), even when they're not actively using it. Welcome to the world of PWA push notifications!
In this article, we'll dive into the technique of implementing push notifications in PWAs, covering everything from VAPID keys to service worker push handlers and permission UX best practices.
Why Push Notifications?
PWAs aim to provide a seamless user experience across multiple devices. With push notifications, you can:
- Alert users about new content or updates
- Enhance engagement with timely reminders and offers
- Increase retention by keeping users informed
Let's get started!
The Technique: VAPID Keys and Service Worker Push Handler
To implement PWA push notifications, you'll need to follow these steps:
- Generate VAPID keys: Obtain a pair of Validation Tokens (vapidkeys) from your server. These are used to validate incoming messages.
- Register the service worker: Register a service worker to handle incoming push messages.
- Request permission: Prompt users for permission to display notifications.
VAPID Keys: The Secret Sauce
VAPID (Validated Access Push) keys ensure that only authorized servers can send push notifications to your users' devices. You'll need to generate a pair of VAPID keys using the following TypeScript code:
import { vapidKeys } from 'web-push';
const publicKey = vapidKeys.generatePublicKey();
const privateKey = vapidKeys.generatePrivateKey();
console.log(publicKey); // Output: public key
console.log(privateKey); // Output: private key
Service Worker Push Handler
Create a service worker to handle incoming push messages. This code snippet demonstrates how to register the service worker and set up the push handler using JavaScript:
navigator.serviceWorker.register('sw.js')
.then(registration => {
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: 'YOUR_PUBLIC_VAPID_KEY'
})
.then(subscription => {
console.log(subscription);
});
});
Permission UX Best Practices
When requesting permission to display notifications, follow these guidelines:
- Be clear: Explain what users can expect from push notifications.
- Provide an opt-out: Allow users to disable notifications at any time.
Here's an example of a permission request prompt in PowerShell:
$notificationPermission = Register-ObjectEvent -InputObject $sw -EventName "pushmessage" -SourceIdentifier 'PushMessage'
if ($notificationPermission) {
Write-Output 'Notification permission granted!'
} else {
Write-Output 'Notification permission denied.'
}
Concrete Examples
Example 1: News Feed App
A news feed app can use push notifications to alert users about new articles.
- VAPID keys: Generate a pair of VAPID keys for the news feed server.
- Service worker: Register the service worker in the PWA, setting up the push handler with the public VAPID key.
- Permission request: Prompt users for permission to display notifications when they first launch the app.
// sw.js (service worker)
self.addEventListener('push', event => {
if (!event.data) return;
const notification = event.data.json();
self.registration.showNotification(notification.title, {
body: notification.message,
icon: 'favicon.png'
});
});
Example 2: E-commerce App
An e-commerce app can use push notifications to remind users about abandoned carts or promotions.
- VAPID keys: Generate a pair of VAPID keys for the e-commerce server.
- Service worker: Register the service worker in the PWA, setting up the push handler with the public VAPID key.
- Permission request: Prompt users for permission to display notifications when they first launch the app.
// index.js (main code)
navigator.serviceWorker.register('sw.js')
.then(registration => {
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: 'YOUR_PUBLIC_VAPID_KEY'
})
.then(subscription => {
console.log(subscription);
});
});
When NOT to Use Push Notifications
- Background tasks: Avoid using push notifications for background tasks, as they can be intrusive.
- Simple updates: Don't use push notifications for simple updates or changes in the app.
Related Apiary Lessons
Honey, I'm Home!
Implementing PWA push notifications is a sweet way to enhance user engagement and retention. By following these steps and guidelines, you'll be well on your way to creating a buzz-worthy experience for your users!
Happy building!