Understanding the Web Push API

featured article thumbnail

Web push notifications are a great way to stay in touch with your customers without asking them to download another app. Built on the web platform, this technology enables push notifications across different browsers and frameworks. 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. A push server acts as the backend component responsible for managing push subscription endpoints and delivering push messages to clients. 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.

What Is the Web Push API?

Person receiving a web push notification on a smartphone

An (API) 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. Push messaging is the process of delivering real-time notifications or data from your server to the user's device using this API.

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. Notifications can be sent even when the website isn't open, regardless of whether the web app is active in a browser window or not.

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. When a new message arrives, a push event is triggered in the service worker to process and display the notification. 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

Andrea Piacquadio

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. You will also need to generate vapid keys.

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. To do this, you need to create a service worker script (e.g., service-worker.js) that will handle push events and notifications. Here’s what the service worker registration looks like in JavaScript:

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

Managing service worker registrations is important for handling updates and multiple push subscriptions effectively.

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().permission => {
  if (permission === "granted"// Permission granted
  }
});

An event handler is used here to process the user's response to the permission request, ensuring that notifications are only sent when permission is granted.

Step 3: Create a Push Subscription

A push subscription specifies where you’ll send the notifications and contains all the information needed to deliver push messages securely. The subscription includes the public key, which is required for the subscription and is part of the VAPID key pair. VAPID keys are used to authenticate push requests and should be securely generated and stored.

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

You can generate VAPID keys using libraries like web-push, and this step is necessary to establish secure communication and authenticate your pushes.

The subscription is created on the client and sent to the push server for storage. The subscription object includes the auth value as part of the subscription data for authentication.

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

All requests to the push server must be properly formatted. The payload size of the notification must be within allowed limits to avoid errors. You can set the message expires parameter to control how long the push message is stored if it cannot be delivered immediately. When sending requests, include an authorization header (such as a signed JWT) and specify the content encoding for secure and authenticated requests.

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

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

After sending, check the response and status code to verify successful delivery of the 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', eventconst data = event.data ? event.datatext() : 'No payload';
  const options = {
    body: data,
    icon: '/images/icon.png',
    badge: '/images/badge.png'
  };
  event.waitUntil(self.registration.showNotification'Title', options));
});

You can also handle 'silent push' events in the service worker, which do not show a user-visible notification. However, be careful to avoid privacy issues and ensure compliance with platform requirements.

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. Delivering notifications in a timely fashion is crucial for user engagement. Check how your notifications display on different browsers, including other browsers like Chrome, Firefox, and Edge, as well as Safari, to ensure compatibility across platforms. Always test notifications directly on the user's device to confirm proper delivery and appearance. When testing on mobile, optimize your implementation to preserve battery life by minimizing unnecessary processing. Note that you do not need to join the apple developer program to implement web push notifications on iOS—Web Push APIs can be used independently. If you use a tool or library for testing, consider whether a new version is available, as it may offer improved support for web push notifications. Check out this step-by-step guide to testing web push notifications to make testing a breeze with a demo of standards-based web push notifications across all platforms, even iOS.

Application Server and Security

The application server is the backbone of any web push notification system, acting as the trusted intermediary between your web app and the push notification services. To keep your push messages secure and reliable, it’s crucial to implement robust security measures on your application server. This starts with generating a key pair—private and public keys—that are used to authenticate your push notifications and encrypt sensitive data. Store these keys securely and never expose your private key in client-side code.

All communication between your application server and push notification services should use secure protocols like HTTPS to protect user data and prevent unauthorized access. Validating each push subscription before sending notifications helps ensure that only legitimate users receive your messages. Leveraging a web push library on your application server can streamline subscription management and simplify the process of sending push notifications, handling much of the complexity behind the scenes. By prioritizing security and proper subscription management, you can build trust with your users and maintain the integrity of your push notification system.


Sending a Push

Once your application server is set up and secure, sending a push notification involves a few key steps. First, the server generates a JSON Web Token (JWT) to authenticate itself with the push service. Next, the notification payload is encrypted using advanced cryptographic techniques like Elliptic Curve Diffie-Hellman (ECDH) and HKDF, ensuring that only the intended user can decrypt and read the message.

With authentication and encryption in place, the application server sends the push message to the appropriate push service, following the Web Push Protocol. The push service then delivers the message to the user’s device, where the service worker decrypts and displays the notification. To send a push notification, your server must have access to a valid push subscription and the necessary keys for encryption and authentication. By adhering to the Web Push Protocol, you ensure that your push messages are compatible with all major browsers and push services, providing a seamless experience for your users.


Sending Web Push Notifications with MagicBell

MagicBell simplifies sending web push notifications. The MagicBell SDK provides a WebPushButton that can be used subscribe or unsubscribe a user to web push notifications.

The WebPushButton uses the Push API to register or remove the user's subscription. There are no redirects. The button supports custom labels, styling, and ref forwarding.

To enable web push, your service worker must import MagicBell's script:

importScripts('https://assets.magicbell.io/web-push-notifications/sw.js');

You can learn more about how to use the WebPushButton component in your own app in the MagicBell SDKs docs.

For example, to use the WebPushButton component in your React app:

import * as React from "react";
import Provider from "@magicbell/react/context-provider";
import WebPushButton from "@magicbell/react/webpush-button";
import "@magicbell/react/styles/floating-inbox.css";


function App(props: any) {
  return (
    <Provider token="${USER_JWT}">
      <WebPushButton
        renderLabel={({ status, error }) =>
          error || (status === "success" ? "disable" : "enable")
        }
      />
    </Provider>
  );
}

export default App;

Backwards Compatibility

Ensuring that your web push notifications reach all users, regardless of their browser or device, is essential for a robust notification strategy. While the Web Push API and Web Push Protocol offer a standardized approach, not all browsers—especially older versions—support these technologies. To address this, consider implementing a fallback mechanism, such as a polyfill or a web push library that provides backwards compatibility. This helps guarantee that your push messages are delivered and displayed correctly, even on browsers that lack full support for the latest standards.

Using a declarative push message format can further enhance compatibility, ensuring that notifications render properly across different environments. By planning for backwards compatibility, you maximize the reach of your push notifications and provide a consistent user experience, no matter how your users access your web application.


Best Practices for Push Notifications

To make the most of web push notifications, it’s important to follow industry best practices. Always obtain explicit user consent before sending push notifications, and make sure your messages are clear, concise, and relevant. Respect user preferences by allowing them to manage their subscriptions and easily unsubscribe if they choose. Effective subscription management not only improves the user experience but also helps maintain a healthy relationship with your audience.

Utilizing a web push library can simplify the process of sending notifications and managing subscriptions, ensuring that your implementation follows the Web Push Protocol and adheres to current standards. By focusing on user-centric messaging and responsible subscription management, you can boost engagement while minimizing the risk of users blocking or ignoring your notifications.


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. Web push notifications are designed to deliver information directly to the end user, even when the web app is not open. 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. and send notifications in as little as one hour.

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. The notifications api is used to display notifications on both mobile and desktop devices.

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. This is possible because push messaging allows servers to send notifications asynchronously, ensuring messages are delivered even if the user is offline at the time, and are shown once connectivity is restored.

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. When a notification expires or can no longer be delivered, the push service removes it.

Conclusion

Push notifications are a powerful way to engage users and deliver timely information directly to their devices. By understanding the Web Push API, the Web Push Protocol, and the importance of a secure application server, you can create a reliable and effective push notification system for your web application. Leveraging a web push library and following best practices for subscription management and user consent will help ensure your notifications are delivered securely and respectfully.

As the web push ecosystem evolves, staying informed about the latest standards and techniques will keep your push notification strategy ahead of the curve. By prioritizing security, compatibility, and user experience, you can create innovative push notification systems that not only reach your users but also enhance their interaction with your web app.