DEV Community

NasreenKhalid
NasreenKhalid

Posted on

Push Notifications with React JS and Firebase

Push notifications are an essential part of different marketing campaigns when it comes to digital business.

Today we will try to send push notifications setup in Firebase to our react app.

Create firebase project

Let's start by creating a new project in firebase and generate the firebaseConfig variable having all the important information as shown below:

Image description

Now in your React app >> src directory, create a firebase-config.js file and add the following code:

import { initializeApp } from "firebase/app";

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_BUCKET_ID",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID",
  measurementId: "YOUR_M_ID",
};

// Initialize Firebase
export const firebase = initializeApp(firebaseConfig);

Enter fullscreen mode Exit fullscreen mode

Now we need to generate a token from our react app which will help us to generate our notification from firebase.
For this add the following method in your react app > firebase-config.js

import { initializeApp } from "firebase/app";
import {getMessaging,getToken, onMessage} from 'firebase/messaging';

const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_BUCKET_ID",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID",
  measurementId: "YOUR_M_ID",
};

// Initialize Firebase
export const firebase = initializeApp(firebaseConfig);

const messaging = getMessaging();

export const requestForToken = () => {
  return getToken(messaging, { vapidKey: "YOUR_VAPID_KEY" })
    .then((currentToken) => {
      if (currentToken) {
        console.log('current token for client: ', currentToken);
        // Perform any other neccessary action with the token
      } else {
        // Show permission request UI
        console.log('No registration token available. Request permission to generate one.');
      }
    })
    .catch((err) => {
      console.log('An error occurred while retrieving token. ', err);
    });
};

export const onMessageListener = () =>
  new Promise((resolve) => {    
    onMessage(messaging, (payload) => {
      resolve(payload);
    });
  });
Enter fullscreen mode Exit fullscreen mode

Please note that vapid_key in the above code will be generated by navigating to Firebase console of your project >> Cloud messaging section >> Web Configuration section and generate key pair as shown below:

Image description

Then click on 'Send test message' button and add the token here generated from your react app.

To complete the code in our react app, lets go to the react app again and create a folder Notifications where we'll create a file Notifications.js and call the requestToken method from firebase-config.js as shown below:

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

const Notification = () => {
  const [notification, setNotification] = useState({title: '', body: ''});
  const notify = () =>  toast(<ToastDisplay/>); 
  function ToastDisplay() {
    return (
      <div>
        <p><b>{notification?.title}</b></p>
        <p>{notification?.body}</p>
      </div>
    );
  };

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

  requestForToken();

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

  return (
     <Toaster/>
  )
}

export default Notification

Enter fullscreen mode Exit fullscreen mode

Please note that we have used 'react-hot-toast' library to display our notifications in front-end.

Now when you will run your react app, you will see a token generated in the console which you have to copy/paste in the 'Add an FCM registration token' field in firebase/notification/compose as shown below:

Image description

Clicking on Test button will pop-up the notification on your react app.

Please note that you have to create a firebase-messaging-sw.js file in the public folder of your app where you will add the following code in order to create a service-worker which will run in the background of your app:

// Scripts for firebase and firebase messaging
// eslint-disable-next-line no-undef
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-app.js");
// eslint-disable-next-line no-undef
importScripts("https://www.gstatic.com/firebasejs/8.2.0/firebase-messaging.js");

// Initialize the Firebase app in the service worker by passing the generated config
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_BUCKET_ID",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID",
  measurementId: "YOUR_M_ID",
};

// eslint-disable-next-line no-undef
firebase.initializeApp(firebaseConfig);

// Retrieve firebase messaging
// eslint-disable-next-line no-undef
const messaging = firebase.messaging();

messaging.onBackgroundMessage(function (payload) {
  console.log("Received background message ", payload);

  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: "/logo192.png",
  };

  // eslint-disable-next-line no-restricted-globals
  return self.registration.showNotification(
    notificationTitle,
    notificationOptions
  );
});

Enter fullscreen mode Exit fullscreen mode

Now you can create a test message from firebase and it will show on the react app.

Happy coding...

Top comments (0)