• Sending Web Push Notifications from Node.js
  • Article by Code_ Barbarian
  • Translation from: The Gold Project
  • This article is permalink: github.com/xitu/gold-m…
  • Translator: lsvih
  • Proofreader: Talisk

Using the Service Workers API lets you send push notifications to Chrome directly from the Node.js app. The Web-push NPM module allows you to push messages directly without middlemen like PubNub. Using native JavaScript on the front end and the Express framework on the back end, this article will walk you through a “Hello, World” level example of how to do Web push notifications. The final result is shown below. The full source code for this project is available on GitHub.

Authenticate and configure the server

To set up web push, you must first create the VAPID keys. The VAPID Keys are used to identify who sent the push message. NPM’s Web-push module can help you generate VAPID Keys. We will install web-push and its dependencies and use web-push generate-vapid-keys to create the VAPID Keys.

$NPM install [email protected] [email protected] [email protected] [email protected] + [email protected] + [email protected] + [email protected] + [email protected] added 62 Packagesin1.42 s $$. / node_modules/bin/web - push the generate - vapid - keys = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Public Key: BOynOrGhgkj8Bfk4hsFENAQYbnqqLSigUUkCNaBsAmNuH6U9EWywR1JIdxBVQOPDbIuTaj0tVAQbczNLkC5zftw Private Key: <OMITTED> ======================================= $Copy the code

If you need to support older browsers, you’ll also need to get the GCM API key, but you won’t need it on the desktop version of Chrome 63 or later.

Now create the index.js file that contains your service. You will need to import the web-push module using require() and configure the VAPID keys. Setting up the VAPID Keys is simple. Just store the VAPID Keys in the PUBLIC_VAPID_KEY and PRIVATE_VAPID_KEY environment variables.

const webpush = require('web-push');
const publicVapidKey = process.env.PUBLIC_VAPID_KEY;
const privateVapidKey = process.env.PRIVATE_VAPID_KEY;
// Change this to your own email address
webpush.setVapidDetails('mailto:[email protected]', publicVapidKey, privateVapidKey);
Copy the code

Next, add an endpoint called /subscribe to the Express application. The JavaScript in the browser will send an HTTP request with a PushSubscription object in the body. To send push notifications with webpush.sendNotification(), you need to get a PushSubscription object.

const app = express();
app.use(require('body-parser').json());
app.post('/subscribe', (req, res) => {
  const subscription = req.body;
  res.status(201).json({});
  const payload = JSON.stringify({ title: 'test' });
  console.log(subscription);
  webpush.sendNotification(subscription, payload).catch(error= > {
    console.error(error.stack);
  });
});
Copy the code

That’s all you need to do to configure the server. You can check out the full code at GitHub. Now we’re going to create the client client. Js and a service worker — worker.js.

Client and Service Worker

First, use the express-static NPM module to configure the Express application to deploy static resources to the client in the top level directory of the service. It is important to call this app.use() only after the /subscribe route has been processed, otherwise Express will not process the route according to your configuration, but instead will look for the subscribe.

app.use(require('express-static') ('/'));
Copy the code

Next, create the index.html file, which will be deployed as the entry point for your application. The only key thing in the file is the

<html>
  <head>
    <title>Push Demo</title>
    <script type="application/javascript" src="/client.js"></script>
  </head>

  <body>
    Service Worker Demo
  </body>
</html>
Copy the code

Now your entrance is ready. Create a file named client.js. This file will tell the browser to initialize your service worker and send an HTTP request to /subscribe. Since browsers that support service workers should also support async and await, async/await is used in the above example.

// Replace public key with your own.
const publicVapidKey = 'BOynOrGhgkj8Bfk4hsFENAQYbnqqLSigUUkCNaBsAmNuH6U9EWywR1JIdxBVQOPDbIuTaj0tVAQbczNLkC5zftw';
if ('serviceWorker' in navigator) {
  console.log('Registering service worker');
  run().catch(error= > console.error(error));
}
async function run() {
  console.log('Registering service worker');
  const registration = await navigator.serviceWorker.
    register('/worker.js', {scope: '/'});
  console.log('Registered service worker');
  console.log('Registering push');
  const subscription = await registration.pushManager.
    subscribe({
      userVisibleOnly: true.// The 'urlBase64ToUint8Array()' function is the same as described in the following url
      // https://www.npmjs.com/package/web-push#using-vapid-key-for-applicationserverkey
      applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
  console.log('Registered push');
  console.log('Sending push');
  await fetch('/subscribe', {
    method: 'POST'.body: JSON.stringify(subscription),
    headers: {
      'content-type': 'application/json'}});console.log('Sent push');
}
Copy the code

Finally, you need to implement the worker.js file that client.js loads. This file is where the service worker logic resides. When a subscriber receives a push message, the service worker receives a ‘push’ event.

console.log('Loaded service worker! ');
self.addEventListener('push', ev => {
  const data = ev.data.json();
  console.log('Got push', data);
  self.registration.showNotification(data.title, {
    body: 'Hello, World! '.icon: 'http://mongoosejs.com/docs/images/mongoose5_62x30_transparent.png'
  });
});
Copy the code

All right! Configure the correct environment variables and start your service:

$ env PUBLIC_VAPID_KEY='OMITTED' env PRIVATE_VAPID_KEY='OMITTED' node .
Copy the code

Go to http://localhost:3000 in Chrome and you should see the push notifications below!

This notification is not only available in Chrome, but also in Firefox using the same code.

The last

Web push is only one of the many benefits brought by service workers. With an NPM module, you can push notifications to most modern browsers. Next time you need to add push notifications to your Web app, remember to use Service Workers!


Diggings translation project is a community for translating quality Internet technical articles from diggings English sharing articles. The content covers the fields of Android, iOS, front end, back end, blockchain, products, design, artificial intelligence and so on. For more high-quality translations, please keep paying attention to The Translation Project, official weibo and zhihu column.