How to Send push notification in Mobile Using NodeJS with Firebase Service ?
Published: 2024-07-08 10:40:32

To implement push notifications using Firebase Cloud Messaging (FCM) in a Node.js application, you need to handle FCM token storage and manage token updates for each user. Here's a step-by-step guide:

### 1. Set Up Firebase in Your Node.js Project
First, you need to set up Firebase in your Node.js project.

i. **Install Firebase Admin SDK:**
   ```bash
   npm install firebase-admin
   ```

ii. **Initialize Firebase in your Node.js app:**
   ```javascript
   const admin = require('firebase-admin');
   const serviceAccount = require('path/to/your/serviceAccountKey.json');

   admin.initializeApp({
     credential: admin.credential.cert(serviceAccount),
   });
   ```

### 2. Save FCM Token for Each User

You need a database to store the FCM tokens. For this example, we'll use MongoDB.

i. **Install Mongoose:**
   ```bash
   npm install mongoose
   ```

ii. **Set Up Mongoose and Define User Schema:**
   ```javascript
   const mongoose = require('mongoose');

   mongoose.connect('mongodb://localhost/your-database', {
     useNewUrlParser: true,
     useUnifiedTopology: true,
   });

   const userSchema = new mongoose.Schema({
     userId: { type: String, required: true, unique: true },
     fcmToken: { type: String, required: true },
   });

   const User = mongoose.model('User', userSchema);
   ```

iii. **API to Save/Update FCM Token:**
   ```javascript
   const express = require('express');
   const app = express();

   app.use(express.json());

   app.post('/save-token', async (req, res) => {
     const { userId, fcmToken } = req.body;

     try {
       let user = await User.findOne({ userId });
       if (user) {
         user.fcmToken = fcmToken;
         await user.save();
       } else {
         user = new User({ userId, fcmToken });
         await user.save();
       }
       res.status(200).send('Token saved/updated successfully.');
     } catch (error) {
       res.status(500).send('Internal Server Error');
     }
   });

   const PORT = process.env.PORT || 3000;
   app.listen(PORT, () => {
     console.log(`Server running on port ${PORT}`);
   });
   ```

### 3. Send Notifications

i. **Function to Send Notification:**
   ```javascript
   const sendNotification = async (userId, message) => {
     try {
       const user = await User.findOne({ userId });
       if (!user) {
         throw new Error('User not found');
       }

       const payload = {
         notification: {
           title: message.title,
           body: message.body,
         },
         token: user.fcmToken,
       };

       const response = await admin.messaging().send(payload);
       console.log('Successfully sent message:', response);
     } catch (error) {
       console.error('Error sending message:', error);
     }
   };
   ```

ii. **API to Trigger Notification:**
   ```javascript
   app.post('/send-notification', async (req, res) => {
     const { userId, message } = req.body;

     try {
       await sendNotification(userId, message);
       res.status(200).send('Notification sent successfully.');
     } catch (error) {
       res.status(500).send('Internal Server Error');
     }
   });
   ```

### Summary

1. **Set up Firebase and MongoDB.**
2. **Create endpoints to save/update FCM tokens.**
3. **Create a function and endpoint to send notifications.**

### Testing

- **Save/Update Token:**
  ```bash
  curl -X POST http://localhost:3000/save-token -H "Content-Type: application/json" -d '{"userId": "user123", "fcmToken": "your-fcm-token"}'
  ```

- **Send Notification:**
  ```bash
  curl -X POST http://localhost:3000/send-notification -H "Content-Type: application/json" -d '{"userId": "user123", "message": {"title": "Hello", "body": "World"}}'
  ```

Make sure you replace `"path/to/your/serviceAccountKey.json"` with the actual path to your Firebase service account key JSON file. Also, ensure your MongoDB instance is running and replace the connection string with your actual MongoDB connection string.

---