In order to handle push notifications we'll need a client that can recieve notifications and a server that can push notifications. These instructions will help setup a barebones notifications server.
Create the folder notifications-server, go into it and setup an empty git repository, then install express and web-push as a base for our barebones server.
mkdir notifications-server
cd notifications-server
npm init
npm install --save express web-push
Make sure you've already done the previous notifications-client setup and you have the public vapid key, like this:
=======================================
Public Key:
ABCDEFG12308120371023...
Private Key:
ZXCHAGRABCDE879098785...
=======================================
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const webpush = require("web-push");
const app = express();
app.use(cors());
app.use(bodyParser.json());
const port = 4000;
app.get("/", (req, res) => res.send("Hello World!"));
// Dummy in-memory store
const dummyDb = { subscription: null };
const saveToDatabase = async (subscription) => {
// Write your db logic here to save it.
dummyDb.subscription = subscription;
};
// The new /save-subscription endpoint
app.post("/save-subscription", async (req, res) => {
const subscription = req.body;
await saveToDatabase(subscription); //Method to save the subscription to Database
res.json({ message: "success" });
});
const vapidKeys = {
publicKey:
"ABCDEFG12308120371023...",
privateKey: "ZXCHAGRABCDE879098785...",
};
//setting our previously generated VAPID keys
webpush.setVapidDetails(
"mailto:YOUR_EMAIL_HERE",
vapidKeys.publicKey,
vapidKeys.privateKey
);
//function to send the notification to the subscribed device
const sendNotification = (subscription, dataToSend) => {
webpush.sendNotification(subscription, dataToSend);
};
//route to test send notification
app.get("/send-notification", (req, res) => {
const subscription = dummyDb.subscription; //get subscription from your databse here.
const message = "Hello World";
sendNotification(subscription, message);
res.json({ message: "message sent" });
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
- Start the notifications server with
node index.js - Start the nofitications-client with
http-server - Open a browser tab for the notifications-client http://127.0.0.1:8080/
- Make sure the cache is cleared, open DevTools and press the Ask permission button
- If the connection is established, a message should be shown
service.js:38 {message: "success"} - Now open a browser tab for the notifications-server http://localhost:4000/send-notification
- A notification from the notifications-client should pop up, and that's it!
For more information and a thorough guide of the techniques, check out this guide