Push notification to the Browser with Reactjs + Nodejs

Tram Ho

I recently heard a friend tell me about a task at work that is how to fire notifications to users via the browser. At that time vs me, the concept was quite vague and I thought that if the application tab was turned off, how to shoot Notification. Then I tried to find out if I could actually do it. In this article, I will share the activities as well as a small illustration that I learn and do about Push notification.

Well, it turned out that this is what I thought for a long time was an advertisement and clicked on Block without even thinking about what it really is. No more lengthy, let’s start to learn about it

Service Worker

I am learning about Push notification on browser. Yes, I did not mistake the article. First of all, let’s have to understand Service Worker first, Service Worker is a script that works in the browser (browser underground) without user interaction. In addition, it is like a proxy that works on the user side.

What can we do with Service Worker?

  • Control Network Traffic!
  • Cache req / res data from which to run the web offline
  • Implement some background running features such as Push notification and background synchronization.
  • Service Worker can only work on HTTPS protocol. You can also work on localhost during development.

In this article, I only focus on Push notification. First we need to understand this Push operation has 2 parts:

  • Push : sending notification from server to application. So you will need a server
  • Notification : Notifications are displayed in the status bar of the phone or in the browser.

Web push notifications flow

We will have 4 main actors in this process:

  • User : User wants to receive notifications
  • Application : The application runs at the user side
  • Service worker : Runs in browser
  • Push Server : The server fires a message to service workers

Explain the flow:

1, The stream starts when the application requires users to agree to display notifications (same as the original image). The user will have several possible scenarios:

  • Do nothing: default and so the notification will not appear
  • Grant: granded notification will be able to display
  • Deny: denied notification will not appear

2, 3, After the user agrees to receive notifications, the application will register a service worker

4, 5, 6, After successful registration, you will create a push notification subscription

7, The application will then send to the server. Of course, the server needs an endpoint subscription to send noti

8, The server will then save that subcription

9. Serer can then send the notification to the service worker.

10, 11, 12, Service will be displayed to the user. Then, if the user clicks on the notification, the server worker will receive that action via the notification click event . It can then trigger some scripts such as web page rendering, API calls, etc.

Code little finger movement

For this example, I will use Nodejs and Reactjs so by default, everyone has some knowledge and installation environment.

Create server

Still the familiar commands create a nodejs + express server and this time there’s a web-push library

Create the index.js file

Create subscriptionHandler.js file to handle push notifications on server side

Script

This server we create 2 api POST /subscription and GET /subscription/:id to register and activate push notifications from the server of course the GET part can be activated by the logic processing in the project as it really is. Adding new products in the sales web, not the client calling an API to fire a notification about you.

Moreover, I also do not use any database so the data will be fixed in the sendPushNotification function. The list of registered clients is also stored in obj subscriptions and distinguished from each other by the generated id from the createHash function.

So the server part is done.

Create the React app

The fastest way to create React initialization is to run the create-react-app command:

I always install the axios library to easily request the server instead of fetching serve to run the web on the build file

Attention

Although it is possible to run a service worker locally, the react requires running from the build file. So, run a service worker on React, you have to run build and start by command. In addition, because the service worker has cache, so to test the best, sometimes delete the browser cache.

Create file usePushNotifications.js (a custom Hook)

So much code @@

  • The first is to check if the browser supports support notification
  • If the push notifications are already supported, proceed to the registers service worker
  • The handler clicks with onClickAskUserPermission to request that the user provide permissions
  • Handler click with onClickSubscribeToPushNotification to create push notification subscription
  • The handler clicks with onClickSendSubscriptionToPushServer to send the push subscription to the server
  • The handler clicks with onclickSendNotification to simulate the server sending you notifications

Next, add some functions to the serviceWorker.js file that has been created already

Note : we add functions

  • askUserPermission to request user rights
  • isPushNotificationSupported to check if the browser supports it (this will check, for example, opening anonymously will not support)
  • server’s pushServerPublicKey
  • createNotificationSubscription to create the Notification Subscription we created the onClickSusbribeToPushNotification event in usePushNotifications.js above

The key to shooting noti in the browser

To create we need 2 parameters

  • userVisibleOnly : Boolean value indicating the server’s push subscription will only be used to display to the user.
  • applicationServerKey : is a Base64-encoded DOMString or ArrayBuffer containing the ECDSA P-256 public key that the following server push notification will use to authenticate.

This is exactly what the createNotificationSubscription function creates and we use to register it on the server.

  • endpoint : is a unique endpoint and is used to route messages that the server sends to the right device.
  • Keys : Used to authenticate and decode messages

So when the server pushes, where is the browser listening? . That is we must override the service-worker.js file. Actually, the serviceWorker.js file serviceWorker.js by the create-react-app is not the service-worker.js that the browser runs in the background, but after the file is built, it will actually appear.

So we have to code more sw.js file sw.js same level vs serviceWorker.js file

The goal is to listen for the event and handle the user clicking on the notification . After that, make a little modification to the package.js file of the build section and add the sw command below to append the sw file to the service-worker.js file.

Finally, the interface. I will take advantage of the App.js file as a demo

The last memory is to run the command:

Demo: after pressing 3 buttons from top to bottom and press the last button to trigger notification firing on the browser

Link github: https://github.com/vinhyenvodoi98/Push_Notification_Nodejs_Reactjs

Reference:

Share the news now

Source : Viblo