Firebase Push Notifications in React – Step By Step Guide

Firebase Push Notifications in React – Step By Step Guide

Firebase provides many features to help develop high-quality apps. FCM Push Notifications (Firebase Cloud Messaging) is one of the features of Firebase to integrate push notifications on different platforms. In modern web app development, Without push notifications, you can’t engage with your users efficiently. In this step-by-step tutorial, I’ll guide you on how to implement firebase cloud messaging for both foreground and background push notifications in react.

Steps to Integrate FCM Notifications in React

  1. Setting up Firebase Project
  2. Create a ReactJS Project
  3. Install firebase NPM
  4. Configure Firebase in ReactJS
  5. Request Notification Permission in Browser
  6. Generate FCM Token
  7. Generate VapidKey FCM
  8. Foreground FCM Notifications
  9. Background FCM Notifications

Setting up Firebase Project

Create a firebase account using your google account and then navigate to Firebase Console. By default, the console will ask you to create a new project. Add your project name and disable google analytics on project creation.

Once project creation is done, Create a web app under that project by giving app nickname and then click the “Register app” button.

After successful app creation, The console will provide you with the firebase SDK installation guide and configuration needed to integrate with appId, apiKey, storage bucket, etc. In the upcoming section, I’ll guide you on how to configure the firebase in your react application.

Watch the following video to get an understanding of how to create a firebase project and firebase web app in the firebase console.

Create React App

Create a react application using create-react-app command using npx.

npx create-react-app fcm-background-ui

Install Firebase NPM

In order to access Firebase core features, we should install firebase SDK using NPM.

npm install firebase

Configure Firebase in ReactJS

To get started with firebase, we have to integrate the firebase configuration into our web application. As a first step, Create a firebase.js file in the src folder and add the following code to the file.

To get the code below with your own API key and other credentials, Navigate to the project settings in the firebase console and select the web app you have created.

import { initializeApp } from "firebase/app";

const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    databaseURL: "YOUR_DATABASE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID",
    measurementId: "YOUR_MEASUREMENT_ID"

const firebase = initializeApp(firebaseConfig);

export default firebase;

Request Notification Permission in Browser

In order to make notifications work in the browsers, You should request your user for notification permission using Notification Web API.

Import the firebase file that we created in your component. Create a function firebaseMessagingInit which is an async function requesting notification permission for the user.

Inside the method, add the following steps

  1. Check if the notification is available in the browser using "Notification" in window, if it’s not available that browser doesn’t support notifications.
  2. Check if permission is already granted using "Notification.permission === "granted", if it’s granted write logic for the next steps.
  3. If permission is not granted, Request permission by using Notification.requestPermission() method of Notification Web API, It’s a promise that will return the permission string value. The string will contain any of the three values, “granted”, “denied” and “default”.

Add useEffect hook with empty dependency in your component, invoke the firebaseMessagingInit function in it.

// import firebase file
import firebase from './firebase';
import { useEffect } from 'react';
function App() {

  const firebaseMessagingInit = async () => {
      if(!("Notification" in window)) {
        console.log("Browser doesn't support Notification")
      } else if (Notification.permission === "granted") {

        // next steps for notifications
      } else if (Notification.permission !== "denied") {
        try {
          const permission = await Notification.requestPermission();
          if(permission === "granted") {
            // next steps for notifications.

        } catch(error) {

    useEffect(() => {
    }, [])

    return <div></div>

export default App();

Generate FCM Token

FCM Token is a unique token to a device generated by Firebase. Using that token, we can send push notifications to the device. To generate a token, use getToken() method from firebase/messaging package.

Import getMessaging and getToken from the firebase/messaging at the top. Inside your component, create a method generateToken() and get cloud messaging instance using getMessaging(firebase). The firebase parameter for getMessaging method is the firebase app that we instantiated in the firebase.js file.

// import getMessaging & getToken
import {getMessaging, getToken} from "firebase/messaging";

// inside component function
  const generateFCMToken = async () => {
    // create messaging instance
    const messaging = getMessaging(firebase);

    // generate FCM Token
    const token = await getToken(messaging, {
      vapidKey: "<YOUR_VAPID_KEY>"

    console.log("GENERATED TOKEN", token)

Generate VAPIDKEY in FCM Firebase Console

The getToken() method needs a messaging instance and vapidKey parameters. You can generate vapidKey in firebase console by navigating to Project settings -> Cloud messaging -> Generate Key Pair.

vapid key generator fcm step 1

Once you are navigated to the project settings page, select Cloud Messaging Tab

Select Cloud Messaging Tab

Under Cloud Messaging Tab, In the Web Configuration section, Select Web Push Certificates and then click on Generate Key Pair button to generate a VAPID key for FCM.

Generate Key Pair in Web Push Certificates
Generated Key Pair in Web Push Certificates

Copy and paste the generated key pair, inside the getToken second parameter object. Once added, check your browser console to check the generated FCM token. Let’s move on to get foreground FCM notifications.

Foreground Firebase Notifications

Foreground FCM notifications will be triggered only if your browser is in the current viewport. In real world scenario, the backend server stores the generated FCM token against the user and triggers a notification using firebase admin SDK.

For brevity, We are going to use the firebase console to trigger notifications to specific FCM Tokens.

Import onMessage method from firebase/messaging in your file and create a method fcmForeGroundMessageListen(messaging) in your component. It accepts messaging instance as a parameter. Inside this method, add onMessage(messaging, callback) that will trigger the callback method whenever the device receives a notification.

 // create method to listen for changes inside your component 
 const fcmForeGroundMessageListen = (messaging) => {
    onMessage(messaging, (payload) => {
      console.log("Notification Data", payload);

  // invoke the above method inside your generateToken method
  const generateFCMToken = async () => {
    const messaging = getMessaging(firebase);
    const token = await getToken(messaging, {
      vapidKey: "YOUR_VAPIDKEY"

    console.log("GENERATED TOKEN", token);


To send a test notification, Navigate to Firebase Console -> Cloud Messaging -> Send First Message, Add “Notification Title” and “Notification Text” and click on the “Send Test Message” button.

The popup will ask you to add FCM tokens, you can copy and paste the generated FCM token from your browser console to the popup and click the “Test” button to send the notifications.

Check your browser console to see the notification payload that we receive in onMessage method.

FCM Console Notification Test

Render Notification UI using React Toastify

In the previous section, we received and logged the FCM notification in the console. Now, let’s make use of the notification information and render it as a toast using react toastify. Install react toastify package using the following command.

npm install --save react-toastify

After successful installation, Add the following imports at the top of your file to import toast-related components & styles.

import { ToastContainer, toast } from "react-toastify";

import "react-toastify/dist/ReactToastify.css";

To show both notification title and body, we have to create a custom component and render that using react toastify. Create a file NotificationToast.js, paste the following code in that file.

import React from 'react';

const NotificationToast = ({ notification}) => {
    return <div>

export default NotificationToast;

The NotificationToast receives notification as props which is an FCM notification data that we are going to pass from the parent component. It’s time to render our custom component inside a toast, Add ToastContainer component inside your main top-level component.

// inside your main component add the following code in JSX
  return (
    <div className="App">
      <ToastContainer />

As you know that for foreground messages, we receive notification payload inside onMessage callback method so to render custom toast, we have to add the following code in our onMessage callback and pass the payload.notification data to our component.

  const fcmForeGroundMessageListen = (messaging) => {
    onMessage(messaging, (payload) => {
      // to render custom notification toast<NotificationToast notification={payload.notification}/>)
      console.log("Notification Data", payload);

Let’s send a test message by using the firebase console to see the preview of our custom component implementation. If you don’t know how to send test notifications from the firebase console, check the previous section.

custom toast notification
Custom FCM Notification Toast Preview

Background Firebase Push Notifications React

Background Firebase Push Notifications are notification that shows when your browser tab is not active. To implement background notifications in web applications, you should implement service workers.

What is Service Worker?

Service workers are specialized JavaScript assets that act as proxies between web browsers and web servers. They aim to improve reliability by providing offline access, as well as boost page performance.

Service workers are used to create progressive web apps, and also we can make use of service workers to trigger some javascript code if the app is not in an active state using this we can trigger push notifications and show the native notification UI as well.

Service Worker For Firebase Push Notification React

Create a file firebase-messaging-sw.js inside your public folder, the service worker files should be placed inside the root of your application so that browser can detect and register that as a service workers.

Inside the file, paste the following code to configure and initialize firebase messaging inside the service worker.


// configure firebase
const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_AUTH_DOMAIN",
    databaseURL: "YOUR_DATABASE_URL",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_STORAGE_BUCKET",
    messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
    appId: "YOUR_APP_ID",
    measurementId: "YOUR_MEASUREMENT_ID"


// create messaging instance
const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
    const notificationTitle = payload.notification.title; 
    const notificationOptions = {
        body: payload.notification.body,
    return self.registration.showNotification(notificationTitle, notificationOptions);

In the above code, we are configuring firebase and creating a messaging instance. Firebase provides onBackgroundMessage method which accepts a callback that triggers every time we receive a notification when the web app is not in the foreground.

We can get the notification title and body from the payload and pass that to self.registration.showNotification(notificationTitle, notificationOptions) to show a native OS notification UI.

To test our background FCM Notification, send a test notification using the firebase console. You will get a similar kind of notification as below.

FCM Background Notification Preview

FCM Background Notifications are not showing?

If you have done all the above steps, still FCM Notifications for web applications are not shown in the background. Check the following points and resolve that.

  1. Check if notifications are enabled in your browser for your website.
  2. Check notifications are enabled in your OS for that particular browser.
  3. Make sure that you placed your service worker file inside the public folder of your react application and the name should be “firebase-messaging-sw.js”.
  4. Check service workers are properly registered by going to dev tools -> Application -> Service Worker. It shows you the service workers in your application. If it’s in a stopped state, click on start.
  5. If your service worker code seems not updated, click on the update button or unregister/register the service worker again to get the latest changes.
Stopped state Service Worker inside Chrome Dev Tools


In this detailed step-by-step tutorial on Push Notification integration in React using Firebase, we covered how to set up a firebase account and integrate both foreground and background notifications and also we covered how to test the notification using the firebase console without backend integration.

Here’s a full code repository of our sample project, Firebase Push Notifications in React Github Repo. I hope, this helps to solve your problem. If you face any issues in firebase integration, please feel free to comment here I’ll help you.