Angular Push Notifications
What we know as Web Push Notifications are actually based on two separate browser standards:
-
Push API - this is an API that allows messages to be pushed from a server to a browser (even when the site isn't focused or the browser is closed)
-
Notifications API - displays native system notifications to the user
The Push API is what allows the message to be pushed from a server to the browser, and the Notifications API is what allows the message to be displayed, once it gets to the browser.
But notice that we can't push notifications from our server directly to the user's browser. Instead, only certain servers that browser development companies (like Google, Mozilla, etc.) specifically choose will be able to push notifications to a given browser.
These servers are known as a Browser Push Service. Note that for example, the Push Service used by Chrome is different than the one used by Firefox, and each Push Service is under control of the corresponding browser company.
The first thing that we should do is to uniquely identify our server to the several Browser Push Services available. We will then start by uniquely identifying our Application server using a VAPID key pair.
What is a VAPID key pair?
VAPID stands for Voluntary Application Server Identification for Web Push protocol. A VAPID key pair is a cryptographic public/private key pair that is used in the following way:
- the public key is used as a unique server identifier for subscribing the user to notifications sent by that server
- the private key needs to be kept secret (unlike the public key) and its used by the application server to sign messages, before sending them to the Push Service for delivery
Generating a VAPID key pair using node web-push Let's start by generating a VAPID key using the node webpush library. We will first install the webpush library globally, as a command line tool:
npm install web-push -g
We can then generate a VAPID key pair with the following command:
web-push generate-vapid-keys --json
We can now use the VAPID Public Key to subscribe to Push Notifications using the Angular Service Worker.