Table of Contents
Push notifications are a powerful way to engage users by delivering timely updates directly to their devices. Implementing push notifications in web apps hosted on Vercel can enhance user experience and retention. This guide walks you through the key steps to add push notifications to your Vercel-hosted application.
Understanding Push Notifications
Push notifications are messages sent from a server to a user’s device, even when the user is not actively using the app. They can inform users about new content, updates, or important alerts. Implementing them involves two main components: the service worker and the push API.
Prerequisites
- A Vercel account and a deployed web app
- Basic knowledge of JavaScript and service workers
- HTTPS enabled on your site (Vercel provides HTTPS by default)
- Web Push API support in browsers
Implementing Push Notifications
1. Register a Service Worker
Create a JavaScript file (e.g., service-worker.js) in your public directory. This file will listen for push events and display notifications.
Example service-worker.js:
self.addEventListener(‘push’, function(event) {
const data = event.data.json();
const options = {
body: data.body,
icon: ‘icon.png’,
badge: ‘badge.png’
};
event.waitUntil(self.registration.showNotification(data.title, options));
});
2. Request User Permission
In your main JavaScript file, prompt the user for permission to send notifications.
Example code:
Notification.requestPermission().then(function(permission) {
if (permission === ‘granted’) {
subscribeUser();
}
});
3. Subscribe the User to Push Service
Register the service worker and subscribe the user to push notifications, sending the subscription object to your server for storage.
Example code:
navigator.serviceWorker.register(‘/service-worker.js’).then(function(registration) {
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: ‘
}).then(function(subscription) {
sendSubscriptionToServer(subscription);
});
});
4. Send Push Notifications from Server
Use a server-side script to send push messages to subscribed clients. Libraries like web-push in Node.js simplify this process.
Sample server code (Node.js):
const webPush = require(‘web-push’);
webPush.setVapidDetails(‘mailto:[email protected]’, ‘
webPush.sendNotification(subscription, payload);
Best Practices and Tips
- Always request permission explicitly and explain why.
- Use VAPID keys for authentication and security.
- Test across different browsers for compatibility.
- Handle permission denial gracefully.
Implementing push notifications involves both client-side and server-side work, but it significantly enhances user engagement. With Vercel hosting your app, deploying HTTPS and static assets is straightforward, making it an ideal platform for push notifications.