Node.js send downstream cloud message with Google Firebase

Here is an instruction of using Node.js to send JSON data payload to a client device with Google Firebase Cloud Message service.

firebase_logo

  1. Setup and Configure Google Firebase on the client device (Android, iOS). An Android sample of integration of Firebase core and message can be found here. Locate and note the client device token, and the firebase server key.
  2. On Node.js server side, sending downstream message to Firebase API with NPM package “request“. Sample code can be seen below.
  3. Detail information is documented here (downstream message) and here (Message description)  at Firebase website.
/*
Example of Node.JS to send downstream cloud message with Firebase
NPM package request is needed in this code gist
*/
// Firebase auth key
var serverKey = "Firebase Server Key";
var clientToken= "Client Device Token"
// Payload message data
var deviceId = req.query.deviceId;
var eventName = req.query.eventName;
var value = req.query.value;
var options = {
url: 'https://fcm.googleapis.com/fcm/send',
headers: {
'Authorization': 'key=' + serverKey
},
json: {
"to": clientToken,
"data": {
deviceId: deviceId,
eventName: eventName,
value: value
}
}
};
request.post(options, function optionalCallback(err, httpResponse, body) {
if (err) {
return console.error('ERROR – FIREBASE POST failed:', err);
}
// Success
});

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.