How can I save a device Token using Cloud Functions (Javascript)

Viewed 117

I've managed to push notifications successfully whenever the real-time database changes through FCM, and ultimately through the Firebase Cloud Functions

But I do so by setting a constant with the device token hard-coded in:

const registrationToken = "yuYF4yF3nkj....." 

and then adding it when I fire the notification

return admin.messaging().sendToDevice(registrationToken, payload, options); 

I've also tried to use context.instanceIdToken;within:

exports.pushNotification = functions.database .ref("....") .onWrite((change, context) => {
const TokenID = context.instanceIdToken;
console.log(TokenID); 

But it prints out: "undefined"

How can I read my device's token instead of hard-coding it in, since if I were to share this application I would assume the token for each device would be different.

1 Answers

In order to do this you need to subscribe the devices to a topic so that FCM will know to which devices it needs to send notifications. I recommend you to read this documentation for more details on how to do it, but summing it up you need to:

  • Subscribe the devices you wish to a topic using the following code:

    Messaging.messaging().subscribe(toTopic: "YOUR_TOPIC_NAME")
    
  • Trigger messages to be sent to everyone subscribed to your topic in your cloud function, you can use this code as an example:

    var topic = 'YOUR_TOPIC_NAME';
    
    var message = {
        data: {
            text: 'hello world'
        },
        topic: topic
    };
    
    admin.messaging().send(message).then((response) => {
        console.log('Successfully sent message:', response);
    })
    .catch((error) => {
        console.log('Error sending message:', error);
    });
    
Related