Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Push Notifications in PWA (React.js) Using Firebase

DZone 's Guide to

Push Notifications in PWA (React.js) Using Firebase

In this post, we figure out how to push alerts to the users of PWAs using Google Firebase.

· Web Dev Zone ·
Free Resource

Many sites send notifications to their users through the browser for various events occurring within the web app. We can easily do this using Cloud Messaging, which allows us to send messages to any device using HTTP requests with Firebase.

Here are the basic steps required for pushing the notifications to a web app using Firebase.

Setup

Firstly, it's necessary to have a Firebase account. Once you have an account, go to the 'Create a Project' section.

For this demo, we are creating the project using the create-react-app command.

In addition to this, we need the Firebase library. For that, open your terminal and run the command npm install firebase –save.

Coding

  1. Let’s create a file inside the project directory named push-notification.js. Now we must create a function that initializes Firebase and has the important keys to our project.JavaScript code
  2. Next, we must call the respective function.JavaScript code

        In the above image, the function named initializeFirebase() has been called.

  • Service Worker: A service worker is used as a script that the browser runs in the background, separate from the web app. It is mainly providing data in the form of local storage cache. Even if we refresh the web page, the locally stored cache doesn’t change. JavaScript codeIn the above image, we are importing a service worker (serviceWorker) into the index.js file, where other packages are also imported. Now, after importing it into the index.js file, let’s get that exported by developing a new file called serviceWorker.js, which is served as a service.JavaScript codeIn the register function, the default is used so that user can use any name they want to enter in index.js while importing as a user. For example, we can use “import swore(or any other name) from. /serviceWorker;” instead of “import serviceWorker from. /serviceWorker;JavaScript codeIf (navigator. serviceWorker. Controller) {} =>This is the point from which the updated pre-cached content has been fetched, but the previous service worker will still serve the older content until all the client's tabs are closed. New content is available and will be used when all tabs for this page are closed.
    1. serviceWorker will basically import all the scripts that are needed to show the notifications when your app is running in the background.
    2. It is mandatory to have a firebase-messaging-sw.js file in the location where all the other files are served.JavaScript code
    3. Pass messagingSenderId to the firebase.initializeApp function in this file and push it to the notification.js file as shown above.
  • Requesting Permissions to Notifications: It is best practice to allow the user to choose whether or not they wish to see the notifications. For that, let’s create a function in the push-notification.js file that will make a request and generate a token. For example, the  askForPermissionToReceiveNotifications() function is, first, requesting permission and then going through the getToken() method to generate the token and save it to local storage.JavaScript codeNote: You can also check the generated token in the developer mode=>Application=>LocalStorage=>requestedURL=>notification-token. Now, here you get your desired generated token. The value of notification-token(key) is the example of a generated token.Generated token
    Now, after generating the token we need to call the function. Here, we call it in index.js file wherever we need to generate the token, or you can also call this function on click of a button.

JavaScript code

  • Send the Notifications to the User: For sending notifications to the user, we must make a request to the Firebase API and inform the Firebase API about the token the user will receive.Note: In the below example we use Postman, but, if you are willing to use anything else you are free to do that as well.
  • The steps required to make the request are as follows: 

    1. Firstly, we need to make a POST request to the Google API like https://fcm.google.apis.com/fcm/send, by sending the JSON in the request body.
      Our JSON should look like:Postman

    2. “Click_action” in the above JSON describes the URL and “to” describes the token that gets generated.

    3. In the request header, we need to pass the key as content-type and authorization and the value as application/json and server key of our project, respectively:Image title

This key is the server key which you can find in your Firebase account:

    1. Login to your Firebase account.

    2. Go to the project settings through project Overview settings icon.

    3. Then go to the Cloud Messaging and there you can easily get the server key for your Firebase account.

Here, you just click to send our request to Postman and everything is good to go.

Note: Remember that notification will only appear when your app is in the background or minimized.

Topics:
web dev ,google firebase ,react.js ,push notifications ,postman

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}