DEV Community

Dhiman_aman
Dhiman_aman

Posted on

How to Send push notification in Mobile Using NodeJS with Firebase Service ?

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:

   npm install firebase-admin
Enter fullscreen mode Exit fullscreen mode

ii. Initialize Firebase in your Node.js app:

   const admin = require('firebase-admin');
   const serviceAccount = require('path/to/your/serviceAccountKey.json');

   admin.initializeApp({
     credential: admin.credential.cert(serviceAccount),
   });
Enter fullscreen mode Exit fullscreen mode

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:

   npm install mongoose
Enter fullscreen mode Exit fullscreen mode

ii. Set Up Mongoose and Define User Schema:

   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);
Enter fullscreen mode Exit fullscreen mode

iii. API to Save/Update FCM Token:

   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}`);
   });
Enter fullscreen mode Exit fullscreen mode

3. Send Notifications

i. Function to Send Notification:

   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);
     }
   };
Enter fullscreen mode Exit fullscreen mode

ii. API to Trigger Notification:

   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');
     }
   });
Enter fullscreen mode Exit fullscreen mode

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:
  curl -X POST http://localhost:3000/save-token -H "Content-Type: application/json" -d '{"userId": "user123", "fcmToken": "your-fcm-token"}'
Enter fullscreen mode Exit fullscreen mode
  • Send Notification:
  curl -X POST http://localhost:3000/send-notification -H "Content-Type: application/json" -d '{"userId": "user123", "message": {"title": "Hello", "body": "World"}}'
Enter fullscreen mode Exit fullscreen mode

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.


Top comments (0)