Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save oneEyedSunday/0f6ee1381adc15fcab23d4cafab49177 to your computer and use it in GitHub Desktop.
Save oneEyedSunday/0f6ee1381adc15fcab23d4cafab49177 to your computer and use it in GitHub Desktop.
Express server to send push notifications using weboush
import * as express from 'express';
import {Application} from "express";
const webpush = require('web-push');
const bodyParser = require('body-parser');
const cors = require('cors');
const vapidKeys = {
"publicKey":...,
"privateKey":...
}
webpush.setVapidDetails(
'mailto:xxx@xxx.xxx',
vapidKeys.publicKey,
vapidKeys.privateKey
);
const USER_SUBSCRIPTIONS = [];
const app: Application = express();
app.use(bodyParser.json());
app.use(cors());
app.route('/')
.post((req, res) => {
// for personalization
const { sub, id, email } = req.body;
console.log('Received Subscription on the server from user : ', email);
// Perisst this
USER_SUBSCRIPTIONS.push(sub);
res.status(200).json({message: "Subscription added successfully."});
});
app.route('/subs').get((req, res) => {
res.status(200).json(USER_SUBSCRIPTIONS);
})
app.route('/send')
.post((req, res) => {
console.log('Total subscriptions', USER_SUBSCRIPTIONS.length);
// sample notification payload
const notificationPayload = generateNotification('Title','Summary',
'http://someurl.to.link');
// only send to interested users
Promise.all(USER_SUBSCRIPTIONS.map(sub => webpush.sendNotification(
sub, JSON.stringify(notificationPayload) )))
.then(() => res.status(200).json({message: 'Newsletter sent successfully.'}))
.catch(err => {
console.error("Error sending notification, reason: ", err);
res.sendStatus(500);
});
});
// launch an HTTP Server
const httpServer = app.listen(3000, () => {
console.log("HTTP Server running at http://localhost:3000");
});
// The backend should already know the User id & details
const generateNotification = (title: string = 'Defult Title', body: string, url: string = "Default Url") => {
return {
"notification": {
title, body, icon: "assets/favicons/quabb-default.ico", vibrate: [100, 50, 100],
data: {
"dateOfArrival": Date.now(),
"primaryKey": 1,
actionUrl: url
},
endpoint: url
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment