Push API Tutorial

Push API Tutorial

The Push API allows a web app to receive messages pushed by a server, even if the web app is not currently open in the browser or not running on the device.

What is Push API?

The Push API is a recent addition to the browser APIs, and it’s currently supported by Chrome (Desktop and Mobile), Firefox and Opera since 2016. Microsoft Edge supports it in Preview version and Safari already has its own implementation.

Why should we use Push API?

You can send messages to your users, pushing them from the server to the client, even when the user is not browsing the site. This lets you deliver notifications and content updates, hence better customer engagement. This was one of the missing components of mobile web when compared to Native apps and along with this, offline support as well.


How does it work?

When a user visits your web app, you can trigger a panel asking permission to send updates or receive offers or notifications. A Service Worker is installed, and operating in the background listens for a Push Event. So when there is a new offer or any update that you want to notify, your server sends the notification to the client, and the Service Worker, if given permission, receives a the push event. The Service Worker reacts to this event by triggering the notification.


How do we get started?

The first step towards doing it is getting user’s permission to receive updates or offers from the web app. There are multiple check points in this stage:

  • checking if service workers is supported or not
  • checking if push api is supported or not
  • checking if service workers is installed and up and running
  • request for permission from user
  • once we get permission subscribe to notifications
  • once you subscribe get the Push Subscription object and send it to the server


How does server side work?

Till now we have primarily talked about how client interacts with this browsers api, now we are gonna look at how server’s side work.

Here are the steps involved:

  • Once server receives the Push Subscription object, it then validates and then saves to DB or if there is an error then it returns with alert.
  • If server registers the subscription successfully then it can push a notification to all the subscribers or to any one particular subscriber based on subscriber id.
  • In subscription status is 410 then that user is no longer subscribed to your app, you need to remove that user from DB.


The code stub for the same will be followed soon after this post.

Thanks for dropping by !! Feel free to comment to this post or you can drop an email at [email protected]