# How to send push notifications with Firebase, React and NestJS

Firebase Cloud Messaging (FCM) is a versatile cloud-based messaging platform that empowers app developers to send messages and notifications to users' devices, delivering text, images, links, and more. In this guide, we'll explore the benefits of using FCM and walk you through setting up FCM notifications in your web applications using React.js and Nest.js.

## Benifits of using FCM:-

* **Cross-Platform:** FCM works on Android, iOS, and web apps, simplifying multi-platform messaging.
    
* **Reliability:** FCM is known for its dependable message delivery, even during high-demand periods.
    
* **Cost-Effective:** It offers a free tier suitable for most small to medium-sized apps.
    
* **Security:** Ensure secure communication between servers and devices.
    

**Cloud Integration:** Easily integrates with other Firebase services for enhanced functionality.

### Create Firebase project:

* **Go to the Firebase Console:** Visit the Firebase Console by going to [https://console.firebase.google.com/](https://console.firebase.google.com/).
    
* **Sign In:** Sign in with your Google account. If you don't have one, you'll need to create a Google account first.
    
* **Add a New Project:** Click on the "Add project" button to create a new Firebase project.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694452720910/4362b5f3-8e29-4472-9588-2283f01df719.png align="left")
    
* **Enter Project Name:** Give your project a name. This name should be unique within Firebase, so choose something descriptive.
    
* **(Optional) Set Up Google Analytics:** You can choose to enable Google Analytics for your project. This will help you gather data about your app's usage. You can also enable this later if needed.
    
* **Click "Create Project":** Once you've filled in the necessary information, click the "Create Project" button.
    
* **Wait for Project Creation:** Firebase will set up your project, which may take a moment.
    

**Project Created:** Once the project is created, you'll be taken to the project dashboard, where you can see the below image.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694453243489/1152b72f-38af-4ad7-90e5-6c028bf09803.png align="center")

### How to set up your Firebase project?

Here's a step-by-step guide.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694454826794/db412de5-dbcd-4d05-a409-1c59ca3a8b54.png align="center")

1. Click on web notification button.
    

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694455287296/343637f3-0a58-40ac-8e08-88435477a129.png align="center")

Click on '**Register app**' button.

### Now set up your firebase to your react-app

1. Create your react app.
    
2. Install Firebase in your React app
    
3. Create a firebase.js file inside your src folder.
    
    ```javascript
    const firebaseConfig = const firebaseConfig = {
      apiKey: "YOUR_API_KEY",
      authDomain: "YOUR_AUTH_DOMAIN",
      projectId: "YOUR_PROJECT_ID",
      storageBucket: "YOUR_STORAGE_BUCKET",
      messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
      appId: "YOUR_APP_ID"
    };  
      // Initialize Firebase
      export const app = initializeApp(firebaseConfig);
      export const messaging = getMessaging(app);
    ```
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694455978914/f1383b8e-d952-40de-9468-74161da9badc.png align="center")
    

Replace `firebaseConfig` with your firebase project `firebaseConfig` object.

* open app.jsx.
    
    ```javascript
    import { useEffect } from "react";
    import { messaging } from "./firebase";
    import { getToken } from "firebase/messaging";
    
    import "./App.css";
    
    function App() {
      
      async function requestPermission() {
        const permission = await Notification.requestPermission();
        if (permission === "granted") {
          // Generate Token
          const token = await getToken(messaging, {
            vapidKey: Your_Vapid_key
              // replace with your vapid key,
          });
          console.log("Token Gen", token);
          // Send this token  to server ( db)
        } else if (permission === "denied") {
          alert("You denied for the notification");
        }
      }
    
      useEffect(() => {
        // Req user for notification permission
        requestPermission();
      }, []);
    
      return (
        <div className="App">
          <h1>Push notification service</h1>
        </div>
      );
    }
    
    export default App;
    ```
    
    For the code snippet above, you'll need to generate your project's Vapid key. Here are the steps.
    
    * Go to `Project settings`
        
        ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694457189521/51a78688-b59d-48f1-8859-926ff28317ed.png align="center")
        
* Click on `cloud messaging` option.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694457291101/e94e5d1a-95d4-42d7-852e-61f9349a73f1.png align="right")
    
* Scroll down and click on `Generate key pair`button. This action will generate a string, which will serve as your Vapid key.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694457524208/f12c9130-a0aa-43ef-9554-355d9d36f4a6.png align="center")
    

1. Now, run your React app using the `npm run star` command. Open your console, and you will be able to see that your token has been successfully generated.
    

Create a file firebase-messaging-sw.js in the public folder.

```javascript

importScripts("https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js");
importScripts(
  "https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"
);
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_AUTH_DOMAIN",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_STORAGE_BUCKET",
  messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
  appId: "YOUR_APP_ID"
};

const app = firebase.initializeApp(firebaseConfig);
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);
});
```

Here's a simplified explanation of the code:

* We include two Firebase JavaScript libraries: 'firebase-app.js' and 'firebase-messaging.js.'
    
* We configure Firebase with the 'firebaseConfig' object, which contains various settings for our app.
    
* We initialize the Firebase app and messaging service.
    
* We set up a listener for background messages, which allows our app to receive messages even when it's not in the foreground.
    
* When a background message is received, we log it to the console and extract the notification title, body, and icon.
    
* Finally, we display the notification using the extracted title, body, and icon.
    

This code is essential for enabling push notifications in your web app with Firebase.

### Now set up your firebase with NestJS:-

1. Create nestJS project and install firebase-admin package.
    
    ```javascript
    //run this command 
    nest g resource fcm-notification //for creat fcm-notificatiob module
    npm install firebase-admin // for install firebase-admin to your project
    ```
    
2. Now go to `fcm-notification.Service.ts`
    
    ```javascript
    import { Injectable } from '@nestjs/common';
    import * as admin from 'firebase-admin';
    
    admin.initializeApp({
      credential: admin.credential.cert({
        projectId: PROJECT-ID,  // replace with your app project-ID
        clientEmail: CLIENT-KEY, //replace with your app CLIENT-KEY
        privateKey: PRIVATE-KEy //replace with your app PRIVATE-KEy
      }),
    });
    @Injectable()
    export class FcmNotificationService {
      constructor() {
      }
    }
    ```
    
    Above code, we are importing `admin` is imported as a namespace from 'firebase-admin. Next `admin.initializeApp({ ... })` initializes the Firebase Admin SDK with the provided configuration.  
    To access your Admin SDK configuration details, navigate to your project settings and select 'Service accounts.' From there, you can `generate a new private key` in the form of a downloadable JSON file, which will serve as your admin SDK configuration. For reference, please consult the image below.
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694458885707/f5681c0b-5d7e-4147-999e-daa86c232c1f.png align="center")
    
    Now add sending notification function to your service folder.
    
    ```javascript
    import { Injectable } from '@nestjs/common';
    import * as admin from 'firebase-admin';
    
    admin.initializeApp({
      credential: admin.credential.cert({
        projectId: PROJECT-ID,  
        clientEmail: CLIENT-KEY,
        privateKey: PRIVATE-KEy
      }),
    });
    @Injectable()
    export class FcmNotificationService {
      constructor() {
      }
    
      async sendingNotificationOneUser(token:string) {
        const payload= {
          token: token
          notification: {
            title: "Hi there this is title",
            body: "Hi there this is message"
          },
          data: {
            name:"Joe",
            age:"21"
          }
          }
        return admin.messaging().send(payload).then((res)=>{
          return {
              success:true
          }
    
        }).catch((error)=>{
          return {
            success:false
          }
        })
      }
    }
    ```
    
    The `sendingNotificationOneUser` function sends a notification to a specific user. It uses the user's device token to target them, constructs the notification content (title, body, and additional data), and sends it through Firebase. If successful, it returns `success: true`; otherwise, it returns `success: false`.
    
3. Now go to Fcm-Notification.controller.ts.
    
    ```javascript
    import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
    import { FcmNotificationService } from './fcm-notification.service';
    
    @Controller('firebase')
    export class FcmNotificationController {
      constructor(
        private readonly sendingNotificationService: FcmNotificationService,
       ) {}
    
      @Post('send-notification/')
      async sendNotidication(@Body() body:{ token: string }) {
      const {token}=body
       return await this.sendingNotificationService.sendingNotificationOneUser()
      }
    }
    ```
    
    In the code snippet provided, a route for sending notifications is defined in a NestJS controller. When a POST request is made to '/firebase/send-notification/', the function `sendNotidication` is called. It expects a JSON body with a 'token' field, which is passed to the `sendingNotificationOneUser` function from the `FcmNotificationService`. The result of the notification sending process is returned in the response.
    

### Making a Request with Postman:-

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694459993537/70598746-ee66-47e6-954a-2cc605838b48.png align="center")

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1694460090064/3f2baf72-46f7-470f-8b10-f34a69567df7.png align="center")

That's all for now. I hope you find this tutorial helpful! Feel free to leave feedback or questions below, I would love to hear and work on them. Thank you :)
