Hey there, this is an example of a mini app that I created, to demonstrate web push in Progressive web apps.
To get this app running there are several things you need to do;
- clone this repo and run
yarn
to install packages. - copy the contents of the
.env.example
file and add them to your.env.local
file. - Generate VAPID keys and add them to your
.env.local
file. With the web-push library installed globally, you can run the command below to generate keys from command line.
web-push generate-vapid-keys [--json]
- Make sure to add the public vapid key to this line in the function that subscribes the user to the Push API.
yarn dev
should start the app onlocalhost:3000
. Use ngrok to help you run your app over secure protocol inorder to access Notification API.- If testing on iOS - The app has to be added to your home screen inorder to request for permission to send notifications.
- Upon the user accepting to receive notifications the client's push subscription object will be logged in the terminal
- Make a POST request to
localhost:3000/api/notify
with data received from the push subscription object and a custom message you'd like to send. The properties below are added to your request's body inorder to send a push notification to the subscribed user.
{
"subscription": {
"endpoint": "",
"expirationTime": null,
"keys": {
"p256dh": "",
"auth": ""
}
},
"dataToSend": {
"title": "WaterYourPlantsTuesday®",
"body": "A custom message to send"
}
}
I have published an article with more explanation of what is happening in this example and how you can implement web-push in your own web app.