24

Is there any way to send notifications from FCM from a node.js server?

I haven't found anything about it inside documentation.

Ramkrishna Sharma
  • 6,961
  • 3
  • 42
  • 51
Javier Manzano
  • 4,761
  • 16
  • 56
  • 86

3 Answers3

33

Sending messages through Firebase Cloud Messaging takes calling an HTTP end point as described in the documentation on sending downstream messages.

Something as simple as this could do the trick:

var request = require('request');

function sendMessageToUser(deviceId, message) {
  request({
    url: 'https://fcm.googleapis.com/fcm/send',
    method: 'POST',
    headers: {
      'Content-Type' :' application/json',
      'Authorization': 'key=AI...8o'
    },
    body: JSON.stringify(
      { "data": {
        "message": message
      },
        "to" : deviceId
      }
    )
  }, function(error, response, body) {
    if (error) { 
      console.error(error, response, body); 
    }
    else if (response.statusCode >= 400) { 
      console.error('HTTP Error: '+response.statusCode+' - '+response.statusMessage+'\n'+body); 
    }
    else {
      console.log('Done!')
    }
  });

sendMessageToUser(
  "d7x...KJQ",
  { message: 'Hello puf'}
);

Update (April 2017): you can now also run code very similar to this in Cloud Functions for Firebase. See https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks! but which is the variable YOUR_API_KEY_HERE?? I don't know how to get that key from FCM console... – Javier Manzano Jun 24 '16 at 16:18
  • 2
    In console, Gear icon > Project Settings > Cloud Messaging there you will see your API key (server key). – Arthur Thompson Jun 25 '16 at 16:47
  • 1
    I am trying this out and I dont get an error, but I'm not seeing the notifications either. Is there a possible reason for this? I tried a specific deviceId as well as a topic... the quickstart example uses "/topic/news" so i did that one. *** for ios btw, but the parameters are the same i think... – ingrid Aug 10 '16 at 01:32
  • Hi, have you got a simple sample of this implementation from client side? How can I get the deviceId? – Facundo La Rocca Dec 12 '16 at 14:35
  • How can I send notification to all users (all device Ids)? I can send to single device, using the mentioned method, and working fine. Struggling since 2-3 days and searching all over. @FacundoLaRocca Device Id is the unique id for a specific device which you can get when registering FCM. How exactly you're developing the app? – Ravimallya Feb 13 '17 at 17:20
  • Hi Frank, is there an update to this answer since Google Cloud Next '17? I want to send a message to an iOS/Android phone based on a cloud triggered event (HTTP Request). – Cris Apr 11 '17 at 18:46
  • You could run the same code in a Cloud Function. For an example of that, see https://firebase.google.com/docs/functions/use-cases#notify_users_when_something_interesting_happens – Frank van Puffelen Apr 11 '17 at 20:00
9
//I done by this code using node- gcm module.
//We're using the express framework and the node-gcm wrapper

var express = require('express');
var gcm = require('node-gcm');
//init express
var app = express();
app.get('/push', function (req, res) {
    var message = new gcm.Message({
        data: { key1: 'hello' },
        notification: {
            title: 'SPECOZ Offers1',
            body: 'body_data'
        }
    });

    // Set up the sender with you API key, prepare your recipients' registration tokens.
    var sender = new gcm.Sender('Api_Key');
    sender.send(message, 'device_token', function (err, response) {
        if (err) {
            console.error("Error:", err);


        }

        else console.log("Response:", response);
        res.send(response);
    });

});
app.listen("pass the port number");
Hemant
  • 91
  • 1
  • 1
1
const admin = require('firebase-admin');
  const payload = { 
   notification: {
        title: 'this is title', body: 'this is body'
    },
   data: {
           balance: 100,
          priceplanId: 1235 
  }
}  
const deviceToken ='yourtoekn' | ['yourtoekn'];
admin.messaging().sendToDevice(deviceToken, newpayload)
                .then((_response) => console.log(_response))
                .catch(error => console.log(error));

emphasized text You can send a notification to both ios and Android devices;

Tony Aziz
  • 899
  • 6
  • 4