Sign up
APIs

Understanding the Web Push API: Core Concepts and Implementation

Angela Stringfellow

Last updated on

Web push notifications are a great way to stay in touch with your customers without asking them to download another app. While they’re much more time- and budget-friendly than native apps, you still need technical know-how to send notifications to subscribers’ devices.

They require multiple components, but push notifications just aren’t possible without the web push API. In this article, we’ll explain how the web push API works and the steps to set up a web push API for your website.

In this article:

What Is the Web Push API?

Person receiving a web push notification on a smartphone
Photo by Andrea Piacquadio from Pexels

An application programming interface (API) connects separate applications. This technology makes it possible for programs to communicate with each other. A web push API is a type of API that lives in the browser and allows your website to send notifications — even when users don’t have your website open in their browser.

Without this API, you couldn’t send communications to subscribers’ devices in real time, so it’s a must-have component for any push notification setup.

But web push APIs don’t work alone. You also need a service worker, which is a background script that sends notifications when users aren’t on your website. Once users subscribe to notifications, the push notification API delivers the message to the user’s browser and displays the message.

5 Steps for Implementing the Web Push API

Person smiling while looking at a smartphone, receiving a web push notification
Photo by Andrea Piacquadio from Pexels

APIs can get complicated, but implementing the web push API is relatively straightforward. Before you start, you’ll need a service worker and message content waiting in the wings.

Step 1: Enable the Service Worker

You need a service worker to send push notifications when users aren’t on your website. This is a must-have for registering your push API and sending notifications. Here’s what it looks like in JavaScript:

navigator.serviceWorker.register('/service-worker.js');

Step 2: Ask for Permission

You’re legally required to get subscribers’ consent before sending push notifications. Add this code to ensure you only send messages to consenting users:

Notification.requestPermission().then(permission => {
  if (permission === "granted") {
    // Permission granted
  }
});

Step 3: Create a Push Subscription

A push subscription specifies where you’ll send the notifications. It should look something like this:

navigator.serviceWorker.ready.then(registration => {
  registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: urlBase64ToUint8Array('<Your Public VAPID Key>')
  });
});

You also need to send the subscription to your server using this code:

fetch('/save-subscription', {
  method: 'POST',
  body: JSON.stringify(subscription),
  headers: {
    'Content-Type': 'application/json'
  }
});

From there, you use a service like Node.js to send push notifications to the push subscription:

webpush.sendNotification(subscription, 'Your Push Message');

Step 4: Listen for Events

You’re almost there! Next, tell the service worker to listen to push events that trigger notifications. This tells the API to display the notification to the user. You can set this up with JavaScript:

self.addEventListener('push', function(event) {
  const data = event.data ? event.data.text() : 'No payload';
  const options = {
    body: data,
    icon: '/images/icon.png',
    badge: '/images/badge.png'
  };
  event.waitUntil(self.registration.showNotification('Title', options));
});

Step 5: Customize and Test

It isn’t mandatory, but many businesses like to customize and optimize their web push notifications. Change up the call to action (CTA), display icons, and refine your message content to persuade subscribers to take action.

After you’ve customized the notification to your liking, test the setup to ensure everything works. Check how your notifications display on different browsers, devices, and operating systems to ensure all subscribers receive a world-class experience. Check out  webpushtest.com to make testing a breeze with a demo of standards-based web push notifications across all platforms, even iOS.

The Notification Revolution: Are You In?

Web push APIs are relatively simple to create. The proper setup allows you to stay in touch with your customers no matter where they are. However, a hands-on effort like this takes time and resources that many businesses don’t have.

That’s why more businesses are going with MagicBell. Our intuitive platform simplifies sending push notifications, making it possible to build an all-in-one cross-channel messaging inbox for your customers. Sign up for MagicBell and send notifications in as little as one hour.

Frequently Asked Questions

Do web push notifications work on both mobile and desktop?

Yes. As long as a user subscribes to notifications on their browser, they’ll receive web push notifications on their device. These notifications also work across platforms, including Windows, Android, and Linux.

Do users have to be online to get web push notifications?

No. The great thing about push notifications is that you can deliver the content when the user reconnects to the internet.

What happens if a user doesn't interact with a push notification?

If a user doesn't interact with a push notification, it will remain in their notification center until they clear it or until it expires. You can set expiration times for notifications to prevent old or irrelevant messages from lingering.