Reputation: 69
I need to implement broadcast notification through topics in fcm. I am using firebase-admin to send these. can anyone post the snippet of code to send these notifications through node.js?
Upvotes: 1
Views: 4067
Reputation: 1
Be aware also of this "topic limitations" when sending topic messages:
Topic messaging supports unlimited subscriptions for each topic.
However, FCM enforces limits in these areas:
The frequency of new subscriptions is rate-limited per project.
If you send too many subscription requests in a short period of time, FCM servers will respond with a 429 RESOURCE_EXHAUSTED ("quota exceeded") response. Retry with exponential backoff.
Source: FCM documentation.
Upvotes: 0
Reputation: 49
const topic = "test";
const payload = {
notification: {
title: "New news",
body: "2:45",
},
};
admin
.messaging()
.sendToTopic(topic, payload)
.then((response2) => {
// Response2 is a message ID string.
console.log("Successfully sent message:", response2);
})
.catch((error) => {
console.log("Error sending message:", error);
});
Upvotes: 2
Reputation: 193
First you need to subscribe the user to the given topic
// These registration tokens come from the client FCM SDKs.
var registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// ...
'YOUR_REGISTRATION_TOKEN_n'
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
admin.messaging().subscribeToTopic(registrationTokens, topic)
.then(function(response) {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully subscribed to topic:', response);
})
.catch(function(error) {
console.log('Error subscribing to topic:', error);
});
Then you can broadcast the notification using
// The topic name can be optionally prefixed with "/topics/".
var topic = 'highScores';
var message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
You can read more about it here
Upvotes: 1
Reputation: 1
you will need Firebase project device registration tokens firebase cloud function
working of firebase notification : device to device notification : from device 1 - firebase database(function triggers on writes to Database) -firebase cloud function (the cloud function will send notification to dev 2)- device2
Upvotes: 0