Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 9, 2023 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/e17d6c9366830c259f2195c5a41dc0d8 to your computer and use it in GitHub Desktop.
Save code-boxx/e17d6c9366830c259f2195c5a41dc0d8 to your computer and use it in GitHub Desktop.
NodeJS Push Notifications

NODEJS PUSH NOTIFICATIONS

https://code-boxx.com/push-notifications-nodejs/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Save the images below as i-banner.png and i-ico.png.
    • Install the required modules npm i express body-parser web-push
    • Generate the VAPID keys - node 1-vapid-keys.js
  2. Copy the public key into 2-perm-sw.html - const publicKey.
  3. Copy both keys into 4-server.js - publicKey privateKey. Also change mail to your own.
  4. Run node 4-server.js, access http://localhost.

IMAGES

i-banner i-ico

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

const vapidKeys = require("web-push").generateVAPIDKeys();
console.log(vapidKeys);
<!DOCTYPE html>
<html>
<head>
<title>Push Notification</title>
<meta charset="utf-8">
</head>
<body>
<script>
// (A) OBTAIN USER PERMISSION TO SHOW NOTIFICATION
window.onload = () => {
// (A1) ASK FOR PERMISSION
if (Notification.permission === "default") {
Notification.requestPermission().then(perm => {
if (Notification.permission === "granted") {
regWorker().catch(err => console.error(err));
} else {
alert("Please allow notifications.");
}
});
}
// (A2) GRANTED
else if (Notification.permission === "granted") {
regWorker().catch(err => console.error(err));
}
// (A3) DENIED
else { alert("Please allow notifications."); }
}
// (B) REGISTER SERVICE WORKER
async function regWorker () {
// (B1) YOUR PUBLIC KEY - CHANGE TO YOUR OWN!
const publicKey = "YOUR-PUBLIC-KEY";
// (B2) REGISTER SERVICE WORKER
navigator.serviceWorker.register("3-sw.js", { scope: "/" });
// (B3) SUBSCRIBE TO PUSH SERVER
navigator.serviceWorker.ready
.then(reg => {
reg.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey
}).then(
// (B3-1) OK - TEST PUSH NOTIFICATION
sub => {
fetch("/mypush", {
method: "POST",
body: JSON.stringify(sub),
headers: { "content-type": "application/json" }
})
.then(res => res.text())
.then(txt => console.log(txt))
.catch(err => console.error(err));
},
// (B3-2) ERROR!
err => console.error(err)
);
});
}
</script>
</body>
</html>
// (A) INSTANT WORKER ACTIVATION
self.addEventListener("install", evt => self.skipWaiting());
// (B) CLAIM CONTROL INSTANTLY
self.addEventListener("activate", evt => self.clients.claim());
// (C) LISTEN TO PUSH
self.addEventListener("push", evt => {
const data = evt.data.json();
// console.log("Push", data);
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
image: data.image
});
});
// (A) SETTINGS - CHANGE TO YOUR OWN!
const port = 80,
mail = "your@email.com",
publicKey = "YOUR-PUBLIC-KEY",
privateKey = "YOUR-PRIVATE-KEY";
// (B) LOAD MODULES
const express = require("express"),
bodyParser = require("body-parser"),
path = require("path"),
webpush = require("web-push");
// (C) HTTP SETUP SERVER
webpush.setVapidDetails("mailto:" + mail, publicKey, privateKey);
const app = express();
app.use(express.static(__dirname)); // serve static files
app.use(bodyParser.json()); // json parser
// (D) SERVE TEST HOME PAGE
app.get("/", (req, res) => res.sendFile(path.join(__dirname, "/2-perm-sw.html")));
// (E) SEND TEST PUSH NOTIFICATION
app.post("/mypush", (req, res) => {
res.status(201).json({}); // reply with 201 (created)
webpush.sendNotification(req.body, JSON.stringify({
title: "Welcome!",
body: "Yes, it works!",
icon: "i-ico.png",
image: "i-banner.png"
}))
.catch(err => console.log(err));
});
// (F) START!
app.listen(port, () => console.log(`Server deployed at ${port}`));
curl https://user-images.githubusercontent.com/11156244/281611056-7b0290bf-eda2-4819-aa92-47777c460d2c.png --ssl-no-revoke --output i-banner.png
curl https://user-images.githubusercontent.com/11156244/281611063-1bf72129-967a-4320-a757-f0ecf5c7b0ac.png --ssl-no-revoke --output i-ico.png
call npm i express body-parser web-push
node 1-vapid-keys.js
curl https://user-images.githubusercontent.com/11156244/281611056-7b0290bf-eda2-4819-aa92-47777c460d2c.png --ssl-no-revoke --output ./i-banner.png
curl https://user-images.githubusercontent.com/11156244/281611063-1bf72129-967a-4320-a757-f0ecf5c7b0ac.png --ssl-no-revoke --output ./i-ico.png
source "npm i express body-parser web-push"
node ./1-vapid-keys.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment