[Fixed] how to send notification to multiple devices using node-fcm

Issue

Notification is not working while app is closed

const token = ["AAASDfsadfasdfaFDSDFSDLFJLSDAJF;DSJFAsdfdsfsdf"];

app.get('/send-notfication', (req, res) => {
        
        var FCM = require('fcm-node');
        var fcm = new FCM(serverKey);
     
        var messageToSend = "Hi there this is message";

        var message = {
         to: token,

         data: {
           ar_message: messageToSend,
         },
        };
        
        fcm.send(message, function(err, response){
            if (err) {
                console.log("Something has gone wrong!", err);
            } else {
                console.log("Successfully sent with response: ", response.results);
                res.send("Successfully sent")
            }
        });
    })

Question is how to set notification title in it ? and notification is not working app is closed neither in background nor in foreground why ?

Solution

Try this way ..

Use "registration_ids" instead of "to" if tokens are in array and pass info into data object.

app.get("/send-fcm-notification", (req, res) => {
  var FCM = require("fcm-node");
  var fcm = new FCM(serverKey);
  var message = {

   registration_ids: token,

    data: {
      title: "Hi there this is title",
      message: "Hi there this is message"
    },

  };

  fcm.send(message, function (err, response) {
    if (err) {
      console.log("Something has gone wrong!", err);
    } else {
      console.log("Successfully sent with response: ", response.results);
      res.send("Successfully sent");
    }
  });
});

Leave a Reply

(*) Required, Your email will not be published