Home > Uncategorized > #WebPush Notifications using #NodeJS or C#

#WebPush Notifications using #NodeJS or C#


Web push notifications allow websites to communicate with their users after the user has left the website. Think of it like collecting an email address from a user. You ask the user to provide their email address, then at some point in the future, you can send a message to your user from your server – even if that user is no longer on your website.

It has three main parts,

  • A website, which subscribes a user to notifications.
  • A server-side script that sends notifcations
  • A service worker js file, which displays notifications when they arrive.

To get started, you need to create a pair of VAPID encryption keys;

npm install web-push -g
web-push generate-vapid-keys

You should then get a response like the following


Public Key:

Private Key:


Now, lets get started on the client-side, your website.

function askPermission() {
return new Promise(function(resolve, reject) {
const permissionResult = Notification.requestPermission(function(result) {

if (permissionResult) {
permissionResult.then(resolve, reject);
.then(function(permissionResult) {
if (permissionResult !== ‘granted’) {
throw new Error(‘We weren\’t granted permission.’);

function urlBase64ToUint8Array(base64String) {
const padding = ‘=’.repeat((4 – base64String.length % 4) % 4);
const base64 = (base64String + padding)
.replace(/\-/g, ‘+’)
.replace(/_/g, ‘/’);

const rawData = window.atob(base64);
const outputArray = new Uint8Array(rawData.length);

for (let i = 0; i < rawData.length; ++i) {
outputArray[i] = rawData.charCodeAt(i);
return outputArray;

function subscribeUserToPush() {
return navigator.serviceWorker.register('service-worker-2.js')
.then(function(registration) {
const subscribeOptions = {
userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(

return registration.pushManager.subscribe(subscribeOptions);
.then(function(pushSubscription) {
console.log('Received PushSubscription: ', JSON.stringify(pushSubscription));
return pushSubscription;


What this does is that it asks the user for permission to send them push notifications, and then subscribes the user to the push notifications using the VAPID public key above.

Note also, that it registers the service worker “service-worker-2.js”, which will be used later to display the notifications once recieved.

The service worker file “service-worker-2.js” should have the following content:

// https://developers.google.com/web/fundamentals/codelabs/push-notifications/
self.addEventListener(‘push’, function(event) {
console.log(‘[Service Worker] Push Received.’);
console.log(`[Service Worker] Push had this data: “${event.data.text()}”`);

const title = event.data.json().title;
const options = {
body: event.data.json().message,
icon: ‘images/icon.png’,
badge: ‘images/badge.png’

event.waitUntil(self.registration.showNotification(title, options));

If you now open this page, accept notifications, and then view the console window, you’ll see an endpoint url, Auth key, and p256dh key, you’ll need all these in the next step.

Now, let’s take a look on the server side. Create a new folder for your node project, and run npm init to create your package.json.

Run npm install web-push  to pull down a library which will help you in this next step.

const webpush = require(‘web-push’);
const vapidKeys = {
privateKey: ‘OnWh44RFgdpwcUPpxgFHwJVMDHdhcPKEajFIR7Epdp4’

const pushSubscription = {

webpush.sendNotification(pushSubscription, ‘Send!’);

You can see both the public and private keys from VAPID are included, also the push subscription includes the endpoint, p256dh and auth keys.

Finally, you call webpush.sendNotification(pushSubscription, ‘Send!’); where “Send!” is your payload.

If you prefer to use C# on your back-end, you need to install via NuGet “WebPush” and “Newtonsoft.Json” and use the following code

var pushEndpoint = @"https://fcm.googleapis.com/fcm/send/fJLc6xP6HIE:APA91bFnK_dv8fdBYSaGx5HnJ7PHc696DcBAfD-5XJ7Vke4INBVWGaGiexaeVBseWiq1opmRrLZ9Z_XxvfZUe3PyryARxUfNAlTtXeOxssszZBTlQdQ2qkvEIsmObsJigrJylTZO0_p2";
var p256dh = @"BGbqvhUQPyC-QSrm_pQ45Als58dKuehPn-mz1PGXzSvghowZJmEroBMIMAVzuc6QB2zxo032H2NSWgzboMhHFK8=";
var auth = @"SvXCMDcjgzkGWjFNNVtMOw==";

var subject = @"mailto:fiach.reid@gmail.com";
var publicKey = @"BIzwHJzJXHkqjncpDVSZGbwbbIvoHT6LH4Z6oIpFwiZyArDPeHMuuQzWo_ncBWzidBhAvI_mh7QWrSndRnaneCE";
var privateKey = @"L4NtEgeRS0gVnvK-qJ6ovvz5LE2onltGdJy1dLhXD7I";

var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

var webPushClient = new WebPushClient();
	var payLoad = new
		message = "Yo mamma!",
		title = "My Website"
	string strPayload = JsonConvert.SerializeObject(payLoad);

	webPushClient.SendNotification(subscription, strPayload, vapidDetails);
catch (WebPushException exception)
	Console.WriteLine("Http STATUS code" + exception.StatusCode);
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: