A 5-minute guide to Push notifications in Progressive Web Apps

Sep 22, 2020 - 10 min read
Ryan Thelin
editor-page-cover


Progressive Web Apps (PWAs) are sweeping the industry due to their ease of use and fast development process. When combined with Push notification capabilities, these PWAs become a powerhouse for personal and professional developers alike.

Today, we’ll continue our exploration of PWAs by learning what makes Push notifications so helpful and show you how to implement basic Push capabilities in your own apps. By the end, you’ll know Push best practices and have built a Push service starting point for your own project.

Just starting out with PWAs? Read the first part of this series to learn the basics before you continue here: Build modern, offline apps with Progressive Web Apps.


Here’s what we’ll learn today:


Master the fundamentals of Progressive Web Apps

Invest in the basics of PWAs with in-depth, text-based explanations and interactive examples.

Zero to Hero with Progressive Web Apps


What are Push Notifications?

A Push notification is a new way to instantly communicate with your users the app is currently closed. Push notifications use two APIs:

  • Notification API
  • Push API

Notification API allows the app to display system notifications to the user while the app is active. The Push API allows the app to display these notifications even when the app is offline. On mobile, Push notifications can even show up if the phone is locked.

Background service workers make it possible to send messages when offline. The app uses Push API to manage a service worker that constantly listens for special Push notifications from the app server. Once a push message is received, the service worker “pushes” the notification to the user whether the app is currently running or not.

Push notifications can only function if the app has background access to the device and uses a browser that supports Push API. Users must grant background access to apps through a prompt and can disable access at any time.

Most browsers support Push API like Chrome, Safari, and Firefox. Unsupported browsers like Microsoft Edge have announced they will add Push support in future versions.


Common uses of Push Notifications

Push notifications are a powerful tool to re-engage with past users and consistently reach out to current subscribers. They’re best used on apps with time-sensitive components like sales or breaking news. Push notifications have become especially popular with e-commerce apps and news services for their ability to constantly engage customers.

Here are some popular app types that use Push notifications:

  • News apps (CNN, New York Times, NPR): “BREAKING NEWS: This news is breaking”
  • Ecommerce apps (eBay, Amazon.): “Get this product for just $1”
  • Entertainment (Netflix, Youtube, Apple Podcasts): “New episode available now”
  • Rideshare (Lyft, Uber, Grabtaxi): “Your ride is here!”
svg viewer

Pros and Cons of Push Notifications

Pros:

  • Instant notifications
  • Can reach a massive number of users
  • Returns metrics like how many users clicked the notification
  • Can engage with past users even if they don’t actively use the app anymore

Cons

  • Must be used sparingly so users do not opt-out of Push notifications
  • Can undo positive branding. Some users dislike push notifications and may dislike apps that use it.
  • Heavily regulated by providers like Apple.

Quick Guide to Push Terms

  • Push Message: message sent from the server to the client.
  • Push Notification: Notification that is generated from the Push Message to be delivered to the user.
  • Notification API: Interface to configure and display notifications to the user.
  • Push API: Interface to link apps with Push service and allows service workers to receive push messages.
  • Web Push: Web-based push notification implementation.
  • Push Service: Browser specific system for handling push messages. Most are standardized for app development, with the only changes being behind the scenes.
  • Web Push Protocol: Instruction created by the app developer for how an application or user will interact with the browser’s push service.
svg viewer

Best Practices for Push notifications

Push notifications can hurt user experience if used unwisely. Use our list of 5 Push best practices to ensure you get the most out of this new outreach system.


1. Send less than 5 notifications per week

Research sources find different breakpoints for notification frequency, but most have concluded that Push notifications should be used rarely. The exact effectiveness of each message depends on the genre of the app and the chosen medium. As a general rule, never send more than one push notification per day and try to send less than 5 Pushes per week.


2. Opt-in rather than opt-out

Most users prefer the ability to opt-in to push notifications rather than opt-out. Apps that use opt-out are consistently more disliked than apps with opt-in models. Further, many providers like Apple require app developers to use opt-in models for Pushes as part of their guidelines.


3. Soft opt-in over hard opt-in

Hard opt-in is when a user is prompted to grant access the moment they open the app. Soft opt-in is when the prompt is triggered by user action, like when they click a notification button. The latter is favored because it provides more information on what notifications the user can expect. It is seen as less intrusive and offers the chance to ask the user to opt-in on their next visit.


4. Include robust notification settings

Include separate notification settings for push and non-push notifications as well as for different functions on the app. For example, imagine your app shows news articles and allows you to buy news subscriptions for premium articles. The user should be allowed to opt-out of Push notifications from one feature, like subscription offers, but still receive Push notifications on news articles. Similarly, the user should be able to choose to receive email notifications even if they don’t want Push notifications.

Both of these designs ensure that you avoid an all-or-nothing choice for the user and thus maintain maximum product exposure across all types of users.


5. Meet platform guidelines

More and more providers now regulate Push notifications on their platforms, like Apple for iOS. Be aware of where your app will launch and check that it meets all guidelines. Apps that fail to meet guidelines are banned from the platform. Two consistent guidelines across platforms are:

  • Push notifications must not be required for the app to function.
  • Push notifications must not send sensitive or confidential information.
svg viewer

How to implement Push Notifications with PWA

Now, we’ll walk you through how to implement basic Push notifications in your own app. The basic functions any Push-enabled app needs are: create a service worker, check permissions, request permissions, and unsubscribe.

After this tutorial, you’ll have created simple Push capabilities that you can build off of as you continue your PWA app development journey.


1. Setup workspace

Before we start, we’ll create our workspace. First, create a JavaScript file called notification.js. This will be where we add all of our code for the other steps. You should also add a reference to this file in your app’s HTML file with the line:

<script src="./js/notification.js"></script>

We’ll also need to set up an easy way to activate service workers. If you want to track your program’s progress through the steps, you’ll need to remove and reload the service worker to see a change.

Use this code to create a service worker at the top of your notification.js file:


if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/service-worker.js');
  });
}

Line 1 above checks if the browser supports service workers. If yes, lines 2 and 3 set the worker to activate once the page is fully loaded. It’s a best practice to delay service worker activation until after the page is loaded. Low-end devices will get errors if workers are activated while the page is loading.

For more information on service workers and abilities, see our previous article, Build modern, offline apps with Progressive Web Apps


2. Check permissions

Now, we’ll set up checks for if the user has enabled Push notifications and if they’re supported on the current browser. If both are supported, we check that the service worker is ready with navigator.serviceWorker.ready on line 14. Finally, we use the built-in .getSubscription function on line 16 to get user subscription information.


function isPushSupported() {
    //checks if user has granted permission to Push notifications
    if (Notification.permission === 'denied') {
      alert('User has blocked push notification.');
      return;
    }

    //Checks if current browser supports Push notification
    if (!('PushManager' in window)) {
      alert('Sorry, Push notification isn\'t supported in your browser.');
      return;
    }

    //Get `push notification` subscription id

    //If `serviceWorker` is registered and ready
    navigator.serviceWorker.ready
      .then(function (registration) {
        registration.pushManager.getSubscription()
        .catch(function (error) {
          console.error('Error occurred while enabling push ', error);
        });
      });
  }

3. Request Permissions

Every app that uses Push notifications must be able to request user permissions. To learn the basics, we’ll use a hard opt-in model request. The subscribePush() function below asks the user if they want to subscribe to push notifications and subscribes them if they agree.

In line 3 we ask the user to subscribe with a popup window. On the user side it will look like:



Then on line 4, we set criteria for when the user will see notifications. For this example, we set the user to see all notifications sent.

Finally, we use lines 6-10 to check that the subscription has gone through and tell the user that they’re successfully subscribed.


  function subscribePush() {
      //Subscribes user to Push notifications
      registration.pushManager.subscribe({
        userVisibleOnly: true //Set user to see every notification
      })
      .then(function (subscription) {
        toast('Subscribed successfully.');
        console.info('Push notification subscribed.');
        console.log(subscription);
      })
      .catch(function (error) {
        console.error('Push notification subscription error: ', error);
      });
    })
  }

4. Unsubscribe

As our final section, we’ll add a way for the user to unsubscribe from Push notifications. The unsubscribePush() function below gets the user subscription ID then removes it from our Push service.

Lines 2-11 use the built-in getSubscription() function to get the subscription information of the user. We use that subscription information on line 13 as input to the unsubscribe() function. This selects and unsubscribes the user from our Push notifications. If all goes correctly, we then print a message to the user that they’ve unsubscribed successfully.


  function unsubscribePush() {
    navigator.serviceWorker.ready
    .then(function(registration) {
      //Get subscription
      registration.pushManager.getSubscription()
      .then(function (subscription) {
        //If no `push subscription`, then return
        if(!subscription) {
          alert('Unable to unregister push notification.');
          return;
        }

        //Unsubscribes user
        subscription.unsubscribe()
          .then(function () {
            toast('Unsubscribed successfully.');
            console.info('Push notification unsubscribed.');
          })
          .catch(function (error) {
            console.error(error);
          });
      })
      .catch(function (error) {
        console.error('Failed to unsubscribe push notification.');
      });
    })
  }


Wrapping up

Congratulations! You now have all the basic functions needed to create a Push service. Your next steps as you develop your app are to create a button for subscription, implement soft opt-in, and draft your first Push notification.

To learn more about Progressive Web Apps, see Educative’s in-depth course, Zero to Hero with Progressive Web Apps. This course provides hands-on experience with PWAs and teaches you about all the tools professionals use to take their apps to the next level. By the end of the course, you will have a strong foundation to build advanced PWA apps and to pursue a career as an app developer that uses the hottest, most current technologies.

Happy Learning!


Keep reading about web and app development


WRITTEN BYRyan Thelin

Join a community of more than 1 million readers. A free, bi-monthly email with a roundup of Educative's top articles and coding tips.

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2