Implementing Push Notifications In React With Firebase: A Step-By-Step Guide

Firebase was acquired by Google in the year 2014. Google made many enhancements to the platform, and it became a one-stop backend-as-a-service solution. Firebase brings high-end Cloud messaging functionality features.

These are quite helpful for getting the alert messages on the client side. Based on a recent report, more than 21.14% of developers have been using Firebase. Hence, this include managing the app notification features.

Push Notifications Features

Google brings many numbers of advanced features such as centralized authentication, Cloud functions, real-time databases, and more. Some of them are part of the Firebase umbrella.

Firebase stands out as a go-to solution to easily manage the App notification. Many web application development involve the notification functionality for getting continuous features. These also involve user interaction features.

Steps To Implement The Push Notifications In ReactJS With Firebase

Push/alert message helps users easily get new updates about the application. The browser captures notifications and then forwards them to the corresponding application for a web app. Firebase also enables cloud messaging functionality, which is suitable for helping to get alert messages.

Below are some of the steps for implementing the Push Notification in ReactJS with Firebase:

  • React project set-up
  • Install Firebase npm package
  • Initialize the Firebase
  • Create a project in the Firebase console
  • Create Firebase-message-sw.js file
  • User Permissions for getting the Notification
  • Testing in Firebase cloud message

Steps To Install Firebase npm Package

Firebase lets you easily develop a full-stack application. These do not require writing a single line of backend code.

npm create-react-app push-notification-demo
cd push-notification-demo

Run the command npm start to run the app

  • Start a new Firebase project
  • Enter a project name
  • Click Continue
  • Select the Firebase account from the dropdown
  • Click ‘Create a new account when you don’t have one
  • Click “Create project.”
  • Move to Firebase initialization in React app
  • Run the following command:
  • npm install Firebase –save
    
  • Initialize Firebase in the project

Steps To Create A Project In The Firebase Console

For initializing the Firebase in the created app, it is quite important to have the Firebase library. Initializing the Firebase simply allows the creation of the file Firebase.js in the src folder. Create a project inside a Firebase console by creating the Firebase.js in the app.

  • Click Web icon () on top-left page
  • Create a project with name – first-cloud-messaging
  • A Firebase project with the name first-cloud-messaging is added to it.

Steps for setting up the Firebase project

  • Go to Firebase Developer Console
  • Sign in with a Google email address
  • Click the ‘Go to Console’ button
  • Navigate to the console overview page
  • Click the “Create a project” button
  • Provide the project’s name
  • Navigate to the project’s overview page
  • Register application on Firebase
  • Generate API keys
  • Click the ‘Web’ icon to register the app
  • Provide app name
  • Click the “Register app” button
  • Copy Firebase configuration code
  • Register your React app

Steps To Configuring The Firebase Cloud Messaging (FCM)

Upon registering the Apps on Firebase, it is quite important to configure Firebase Cloud Messaging (FCM) service.

  • Navigate to the Project settings page
  • Click the Cloud Messaging tab
  • Navigate ‘Web configuration’ section
  • Click the “Generate key pair” button
  • Generate unique key in ReactJS

Firebase Cloud Messaging especially uses the unique Application Identity key pairs. These are suitable options for connecting the external push services. So the developer is required to generate the identity key for quick accessibility.

Set Up The React App

Creating the React app helps to easily implement the Push Notifications using the Firebase. Upon installing the React app, it is quite a convenient option for installing Firebase. These involve the react-hot-toast packages for implementing Push Notifications on the React app.

npm install firebase react-hot-toast

Steps To Configure Firebase And Firebase-Message-Sw.Js File

Configuring the Firebase as well as Cloud Messaging Service plays an important role in all these aspects. These enable the better option for easily implementing the Push Notification on the app. You can simply follow the below instruction for configuring the Firebase.

  • Open developer console
  • Click Project settings
  • Copy the Firebase configuration object
  • Create a new firebase.js file in the src directory

Example

import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from 'firebase/messaging';
const firebaseConfig = {
  apiKey:", " 
authDomain:"  ", 
projectId:"  ", 
storageBucket:"  ", 
messagingSenderId: "",
  appId:"  "
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

You need to replace the firebaseConfig object using the copied Project settings. These allow the code to be easily set up on the Firebase instances. It is quite a convenient option to initialize a Cloud Messaging object for easily accessing the FCM functionality in the app.

Example of firebase.js

export const onMessager = () =>
  new Promise((resolve) => {
    onMessage(messaging, (payload) => {
      resolve(payload);
    });
});

Example of Sendrequest.js

export const Sendrequest = () => {
  console.log("Requesting User Permission......");
  Notification.requestPermission().then((permission) => {
    if (permission === "granted") {
      console.log("Notification User Permission Granted.");


      return getToken(messaging, { vapidKey: `Notification_key_pair` })
        .then((currentToken) => {
          if (currentToken) {
            console.log('Client Token: ', currentToken);
            
          } else {
            
            console.log('Failed to generate the registration token.');
          }
        })
        .catch((err) => {
          console.log('An error occurred when requesting to receive the token.', err);
        });
    } else {
      console.log("User Permission Denied.");
    }
  });
}

Example of pushNotification.js

import React, { useState, useEffect } from 'react';
import toast, { Toaster } from 'react-hot-toast';
import { Sendrequest, onMessageListener } from './firebase';


const PushNotification = () => {
  const [notification, setNotification] = useState({ title: '', body: '' });


  useEffect(() => {
    Sendrequest();
    onMessageListener()
      .then((payload) => {
        setNotification({
          title: payload?.notification?.title,
          body: payload?.notification?.body,
        });
      })
      .catch((err) => console.log('failed: ', err));
  }, []);


  useEffect(() => {
    if (notification?.title) {
      notify();
    }
  }, [notification]);


  const notify = () => toast(<ToastDisplay notification={notification} />);


  return <Toaster />; // The <Toaster /> should be inside the return block.
};


function ToastDisplay({ notification }) {
  return (
    <div>
      <p>
        <b>{notification?.title}</b>
      </p>
      <p>{notification?.body}</p>
    </div>
  );
}


export default PushNotification;

Example of App.js

import logo from './logo.svg';
import './App.css';
import Notification from './Notification'


function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
      <Notification />
    </div>
  );
}


export default App;

Steps To Manage Notifications’ User Permissions

Handling the User Permission is the most important process for receiving the React application. These can be easily accessed from Firebase’s Cloud Messaging service to enable more features.

It involves constantly developing as well as calling request permission methods. These involve enabling the messaging object to excellence. This ensures better ways to handle the user’s attributes for notifications’ permission requests.

  • Get the registration token for the application with the getToken function
  • Replace placeholder Notification_key_pair using actual key pair
  • Open project overview
  • Register the app
  • Web Push Notification in ReactJS with Firebase is enabled
  • Copy FirebaseConfig object
  • Add Firebase.js file

Steps for Testing Firebase Cloud Messaging

Follow the below instructions for testing the push notification:

  • Go to the Firebase console
  • Open the Project Overview page
  • Send ‘test message” button
  • Click on Cloud Messaging
  • Send “first message” button
  • You will get a message stating that the FCM registration token

Schedule an interview with React developers

Conclusion

Firebase has become the 4th most popular Cloud platform. Firebase become the evolving technology for integrating the backend seamlessly. Push Notifications in the applications helps send timely updates, personalized messages, and alerts. Push Notifications ensure continuous user engagement with instant connectivity.

Contact Bosc Tech Labs if you’re looking for the best React app development company; they’ll show you the future of your enterprise. You can hire React development team who are highly experienced and knowledgeable in this cutting-edge technology.

Read our blogs for more information about React.

Frequently Asked Questions (FAQs)

1. How do you use Firebase with React to implement Push Notifications?

Click Create your first campaign, choose Firebase Notification messages, and provide a notification’s title and message. Press the Send test message button under the Device Preview area. To send the Push Notification, paste the client token and add it. Then click Test.

2. What distinguishes Push Notifications from notifications?

The primary distinction between notifications and Push Notifications is that the latter are generated internally by a device system that wishes to give the user information, a reminder, some news or updates, etc.

3. How do I trigger notifications from Firebase?

Send a trial notification message first. But make sure that the application is running in the device’s background. Open the Messaging page in the Firebase console. Choose Create your first campaign if this is the initial message you send. Deploy by choosing Firebase Notification messages.


Book your appointment now

Stay up-to-date with our blogs