Sign up

apps

Using Push Notifications in PWAs: The Complete Guide

Angela Stringfellow

Last updated on

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:

  1. Know your requirements, including HTTPS hosting, service worker, and manifest file.
  2. Configure the service worker.
  3. Request user permissions.
  4. Integrate the push API.
  5. Send notifications from the server.

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:

What Are Push Notifications in PWAs?

Person using a mobile device and a laptop, push notification icons
Photo by TippaPatt from Shutterstock

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.

Why Use Push Notifications for PWAs?

An open laptop with a progressive web app (PWA) on the screen
Photo by Negative Space from Pexels

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:

  • Timely messages: Immediately contact your users with time-sensitive announcements or offers. This is especially helpful for urgent information like flash sales, breaking news, or critical updates.
  • Re-engagement: Notifications remind users to return to the PWA. If people haven’t used the app in a while, a gentle nudge could be all they need to re-engage.
  • Personalization: Did you know PWAs can leverage user data for personalization? With just a few data points, you can send personalized notifications based on user preferences, past behaviors, or location. This makes notifications way more engaging, increasing users' likelihood of engaging with you.

Basic Push Notification Setup

Developer setting up push notifications in PWAs
Photo by baranq from Shutterstock

Once you’ve created your PWA, it’s time to set up push notifications. Follow these five steps to set up basic push notifications.

1. Nail the Requirements First

For starters, you need a few things to set up push notifications. That includes:

  • HTTPS hosting: You must have secure HTTPS hosting. Push notifications transmit sensitive data between the server and the user’s device. HTTPS encrypts this data, keeping it secure.
  • Service worker: This is where the magic happens. A service worker script runs in the background and handles push notification events for you at scale.
  • Manifest file: A PWA needs a manifest file because it gives the browser important application information. Push notifications also need this file to recognize the application on the user’s device.

2. Configure the Service Worker

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)
    );
});

3. Request User Permission

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.

4. Integrate the Push API

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.

5. Send Notifications From the Server

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.

5 Tips for Leveraging the Full Potential of Push Notifications

Developer looking at a computer screen, creating push notifications in PWAs
Photo by Rivage from Unsplash

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.

1. Segment Your Audience

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:

  • Demographics
  • Purchase history
  • Behavior

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.

2. Follow Best Practices for Notification Content

Person receiving a push notification in a PWA
Photo by Charlotte May from Pexels

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:

  • Use rich media: Enhance notifications with images, GIFs, or videos. Visual elements grab attention faster than text and convey your message more effectively. For example, a notification about a new movie release could include a captivating still from the film, while a product promotion might show a short clip of the product in use.
  • Always include a CTA: A call to action button encourages subscribers to take immediate action. For example, a notification about a sale might have "Shop Now" and "Learn More" buttons. This improves the user experience by providing clear next steps and increases the chances of conversion.
  • Encourage interaction: Always allow users to interact with your notifications. This could be through options like "Yes" or "No," swipe actions, or a reply field.

3. Watch Your Timing

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.

4. Use Analytics to Improve Notifications

Hand holding a smartphone receiving push notifications
Photo by RoBird from Shutterstock

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.

5. Ensure Secure Data Transmission

Push notifications process sensitive data, so security should be a priority. Ensure secure data transmission through:

  • End-to-end encryption: Encrypt all data exchanged via push notifications, whether at rest or in transit. This process encrypts all data on the server side before sending, only decrypting it once it reaches the subscriber’s device.
  • Security protocols: Use Transport Layer Security (TLS) to keep data secure while in transit. TLS prevents attackers from intercepting the data while it travels to the user’s device.
  • Framework compliance: Follow regulations like the European Union’s  GDPR or California’s CCPA. These frameworks require explicit consent for data collection and provide users with control over their data. They’re some of the most stringent data privacy regulations in the world, so following these frameworks will set you up for improved security and compliance.

Witness the Magic of PWA Notifications Firsthand

MagicBell screenshot
Screenshot from MagicBell

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.

Frequently Asked Questions

Can you send push notifications to all browsers?

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.

How do I measure the success of push notification campaigns?

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.

Can I customize push notifications based on a user’s location?

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.