firebase Using Admin SDK(Node js)


Example

At first initilize the firebase sdk and admin SDK

const functions = require('firebase-functions');
const admin = require('firebase-admin');

admin.initializeApp({
  credential: admin.credential.cert({
        //your admin credential certificate generated from the console. Follow this [link][1].
    }),
  databaseURL: "https:///<PROJECT_NAME>.firebaseio.com"
});

Create a payload JSON string as in the first example.

var payload = {
              notification: {
                title: "Title of the notification,
                body: "Body of the notification",
              },
              data:{
                //required key value pair
              }
            };

Then call different send methods to send the notification.

For Topic

admin.messaging().sendToTopic("/topic/", payload)
              .then(function(response) {
                console.log("Successfully sent message:", response);
              })
              .catch(function(error) {
                console.log("Error sending message:", error);
              });
            });

For device

admin.messaging().sendToDevice(token, payload).then(response=>{
                       response.results.forEach((result, index) => {
                        const error = result.error;
                        if (error) {
                          console.error('Failure sending notification to', tokens, error);
                        } else{
                          console.log('Sucessfully sent to '+tokens);
                        }
                      });