Keep Reading
If you enjoyed the post you just read, we have more to say!
Progressive web apps (PWAs) allow brands to enjoy the advanced features of a mobile app without spending a lot of time developing it. With a PWA, you can deliver an app-like experience through a web browser, giving customers the sleek interface they expect while making the most of your development resources.
Like apps, PWAs can also send push notifications to give users timely information, regardless of their browser or device. These minimally intrusive notifications send updates directly to a user’s device to bring much-needed engagement to your PWA—without tricky workarounds.
Using push notifications in PWAs isn’t difficult, but setting things up still requires some technical know-how. Whether you’re a developer or a business owner, it’s important to understand how to leverage push notifications in a progressive web app. Setup generally requires a few steps:
In this guide, we’ll translate the technical concepts behind using push notifications in PWAs. We’ll explain why they’re beneficial, share basic steps for setting them up, and offer five tips for leveraging the full benefits of push notifications in PWAs.
In this article:
With PWA push notifications, your server sends push notifications to a user’s device even when they aren’t actively using your web application. The alerts appear just like native app alerts but without the need to download yet another app to the user’s device.
This capability bridges the gap between web-based PWAs and native applications, giving you the power to engage users like you would with a native app.
PWAs use service workers to send push notifications to users. These service workers are scripts that run in the background, separate from a webpage. The script allows you to send alerts without user interaction or a web page.
In other words, PWA push notifications synchronize data in the background, allowing you to send push notifications even if the user hasn’t opened the PWA in their browser.
The downside? With the introduction of the EU’s Digital Markets Act (DMA), Apple removed home screen web apps for iOS users in the EU. This was due to the DMA requiring home screen web apps to be allowed to use alternate web browsers, which Apple believed could allow malicious web apps to gain access to user’s devices.
You went to the trouble of building a PWA; why not get more engagement for your trouble? Push notifications boost user engagement and retention by communicating with them when they aren’t using your web app, maintaining a connection between the user and your company.
Push notifications are helpful for many reasons, but the most compelling benefits are:
Once you’ve created your PWA, it’s time to set up push notifications. Follow these five steps to set up basic push notifications.
For starters, you need a few things to set up push notifications. That includes:
The service worker does most of the heavy lifting in push notifications for PWAs. To set this up, you’ll need to know JavaScript.
In your main JavaScript file, check if the browser supports Service Workers and register it using the navigator.serviceWorker.register() method. Here's an example:
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
}).catch(function(error) {
console.log('Service Worker registration failed:', error);
});
}
Next, go to the Service Worker file (sw.js) and add an event listener for push events. This will handle incoming push messages and display them as notifications:
self.addEventListener('push', function(event) {
const data = event.data.json(); // Assuming the server sends JSON
const options = {
body: data.body,
icon: 'icon.png',
badge: 'badge.png'
};
event.waitUntil(
self.registration.showNotification(data.title, options)
);
});
Now that your service worker script is running, you’ll need to get permission from the user to send notifications to their device. Timing is key. Ask for permission when they’re more likely to say yes.
Instead of bombarding them the minute they visit your PWA, ask after they’ve taken action or engaged with you in some way.
Most PWAs request permission through an in-app permission dialogue, which you can set up like this:
<div id="soft-ask">
Stay updated with the latest news directly on your device. Allow notifications?
<button onclick="subscribeUser()">Yes</button>
<button onclick="hideSoftAsk()">Not now</button>
</div>
If the user grants permission, you can register them for push notifications. But not all users want to receive notifications, so respect their privacy! Always give them the option to change their mind later in their PWA settings.
A push API allows your web application to push messages from the server when the app isn’t live in the browser. The Push API works by establishing a connection with a platform-dependent push notification service (such as Google Firebase Cloud Messaging or Apple Push Notification Service).
You can subscribe users to your push messages with Push API like this:
navigator.serviceWorker.ready.then(function(registration) {
// Check for an existing subscription
registration.pushManager.getSubscription()
.then(function(subscription) {
if (!subscription) {
// No subscription, register now
const applicationServerKey = urlB64ToUint8Array('YOUR_PUBLIC_VAPID_KEY_HERE');
registration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: applicationServerKey
})
.then(function(subscription) {
console.log('User is subscribed:', subscription);
})
.catch(function(err) {
console.log('Failed to subscribe the user:', err);
});
} else {
console.log('User is already subscribed.');
}
});
});
This option checks if the user is already subscribed, helping you avoid duplicate subscriptions or messages.
It’s action time! In the last step, you’ll use server-side technology to send notifications to your subscribers. There are several ways to do this, but Node.js and Python are two of the most popular options.
Let’s say you’re using a web push library with Node.js. The library handles all encryption and communication details for you, making it super easy to send notifications. Here’s an example of the Node.js code:
const webPush = require('web-push');
const vapidKeys = {
publicKey: 'YOUR_PUBLIC_VAPID_KEY',
privateKey: 'YOUR_PRIVATE_VAPID_KEY'
};
webPush.setVapidDetails(
'mailto:example@yourdomain.org',
vapidKeys.publicKey,
vapidKeys.privateKey
);
const pushSubscription = {
endpoint: 'https://fcm.googleapis.com/fcm/send/some-id',
keys: {
auth: 'your-auth-secret',
p256dh: 'your-p256dh-key'
}
};
const payload = JSON.stringify({ title: 'Hello!', body: 'Hello, world!' });
webPush.sendNotification(pushSubscription, payload)
.then(result => console.log('Push sent:', result))
.catch(err => console.error('Error sending push:', err));
Lastly, of course, before you go live, be sure to test it first to ensure everything is working correctly. Check out webpushtest.com to test your web push notifications across all platforms, including iOS.
Setting up push notifications in a progressive web app is easy. If you have the development chops to build a PWA, you’ve got what it takes to send notifications from your app.
However, it’s crucial to follow push notification best practices, whether you’re new to sending notifications or your existing subscribers just aren’t biting. Follow these tips to get the most results from your push notification campaigns.
Your subscribers don’t want to open messages that have nothing to do with them. Effective communication hinges on relevance, and that’s especially true for push notifications. Segment your audience into different lists based on:
Instead of sending the same message to everyone, creating separate lists gives you the power to speak to subscribers more personally. Not everyone will bite, but subscribers are much more likely to respond positively to segmented, personalized content.
Who you message matters, but the content of the message itself is arguably the most essential part of any push notification campaign. You’ll need to refine these campaigns over time to find what sticks, but these content best practices are a great place to start:
Messaging matters, but timing and frequency are also significant factors. Don’t send people dozens of notifications daily—that’s a recipe for mass unsubscribes. Analyzing user behavior to identify peak times can significantly improve response rates, so send notifications when users are most likely to be active.
For a global audience, consider timing your notifications for different time zones.
It’s also smart to set frequency caps. Too many notifications can lead to users opting out, while too few might cause them to forget about your business. When in doubt, allow users to customize their communication frequency preferences in the PWA settings.
The great thing about push notifications is that they collect an immense amount of data on your subscribers’ preferences. Don’t let that data go to waste; analyze it to craft even more effective campaigns in the future.
Use analytics tools to track open rates, interaction rates, and conversion rates from your notifications. This data is invaluable in understanding what works and what doesn’t.
You can also conduct A/B testing (also called split testing) campaigns. With this approach, you test different versions of a notification to see which elements perform the best, whether it’s adjustments to your messaging, images, or timing.
Don’t be afraid to adjust your notification strategy based on what you learn. The more data-driven your decisions, the more likely you’ll see gains in user engagement and app performance.
Push notifications process sensitive data, so security should be a priority. Ensure secure data transmission through:
Progressive web apps balance the convenience of a native app with user expectations. Since users are less likely to visit a web app—especially if it isn’t open on their browser—push notifications are a much-needed lifeline for any PWA that relies on regular engagement.
The process outlined in this blog makes it a cinch to set up push notifications, but there’s an easier way to get started. MagicBell’s real-time push notification inbox for PWAs gives users an all-in-one source for viewing and engaging with your messages.
Did we mention it’s easy to set up? Don’t just take our word for it: Sign up for MagicBell to see our powerful notifications in action.
Yes, to most browsers. Chrome, Firefox, Edge, and Safari all allow push notifications from progressive web apps. However, setting up notifications will differ by browser—especially for Safari, which behaves differently.
Look at analytics on delivery rates, open rates, interaction rates, and conversion rates. Many push notification platforms include tools built into the platform for analyzing your performance, but you can also verify performance with third-party analytics tools.
Yes, provided the user shared their location data with you. Location-based messaging is a great way to send hyper-relevant notifications on weather alerts, local news, or local retail offers.
However, it’s best to give users more control over their data, so allow them to customize the information they share with you in their notification settings.