FCM Integration by shayaliza
Frontend
Step 1. Get the keys and vapid id from firebase console, Enable FCM service, create react App and install firebase package
npm i firebase
Step 2. Create firebase config file in root


import firebase from "firebase/compat/app";
import { getMessaging, getToken } from "firebase/messaging";
import "firebase/compat/auth";
import "firebase/compat/storage";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

firebase.initializeApp(firebaseConfig);

const app = firebase.initializeApp(firebaseConfig);
export const messaging = getMessaging(app);

export const generateToken = async () => {
  const permission = await Notification.requestPermission();
  if (permission === "granted") {
    const token = await getToken(messaging, {
      vapidKey:
        " your vapit key",
    });
    return token;
  }
};

Step 3. Now inside public folder make a file firebase-messaging-sw.js and paste the code

importScripts("https://www.gstatic.com/firebasejs/8.10.1/firebase-app.js");
importScripts(
  "https://www.gstatic.com/firebasejs/8.10.1/firebase-messaging.js"
);

firebase.initializeApp({
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage((payload) => {
  console.log(
    "[firebase-messaging-sw.js] Received background message ",
    payload
  );
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: payload.notification.image,
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

Step 4. Now inside App.js call this function

import { toast } from "react-toastify";
import { onMessage } from "firebase/messaging"; //from firebase package
import { messaging } from "./firebase.config"; //from local file we made as config

function App() {
  onMessage(messaging, (payload) => {
    console.log("payload", payload);
    toast.info(payload.notification.body);
  });

  const AllowNotification =  () => {
    generateToken().then((token) => {
      console.log(token);
      //save this token to DB to send notification using backend
    });
  };

  return (
   <div>
   Hello Page
   <div onClick={AllowNotification}>Button</div>
   </div>
  );
}

export default App;

Step 5. Once we get the token we can easily send message from firebase console Messaging Option
Step 6. To send Message at a specific Condition we have to make backend and from there we send the message, so save the token to DB, In this Blog we are keeping it simple for now
Backend
npm i firebase-admin express cors
Step 7. Create firebase.js file, u will get the serviceAccountKey from firebase console download and attach
const admin = require("firebase-admin");
const serviceAccountKey = require("./serviceAccountKey.json");

const firebaseAdmin = admin.initializeApp({
  credential: admin.credential.cert(serviceAccountKey),
});

module.exports = { firebaseAdmin };
Step 8. Now in any Controller we can easily send the message import firbaseAdmin
const {firebaseAdmin} = require("./firebase"); //our local file we made 
Step 9. Now in Any Controller get the token and use this code
const message = {
            notification: {
              title: "title",
              body: "Notification Body",
            },
            token: your Token,
          };
firebaseAdmin
          .messaging()
          .send(message)
          .then((response) => {
            console.log("Successfully sent message:", response);
           })
          .catch((error) => {
             console.log("Error sending message:", error);
          }); 
Bss Itna hi h
OK BYE