I just got firebase function push notifications working for the first time. I'm monitoring a change with :
exports.observeNotifications = functions.database.ref('/notifications/{user_id}/{notification_id}').onWrite((change, context) => {
Later, I use :
const userQuery = admin.database().ref(`users/${from_user_id}/username`).once('value');
const deviceToken = admin.database().ref(`/users/${user_id}/device_token`).once('value');
to retrieve the sender's userUID and device token which is later used with sendToDevice()
This works fine and is the method I see recommended everywhere, but I'm wondering why to do this over using topics in a user to user scenario.
In the example of a chat application, every time a chat is sent, a value would be sent to notifications/users/{uid} ...
and trigger the event. Then the value calls have to be made, promise handling has to be done, and then the push payload can be configured and sent.
With topics, when the user first loads up the application for the firs time, you could subscribe the user to a topic like "chat_notifications_usersIUID". This negates the need to fetch device tokens and go through the process of using promises and greatly simplifies the process of sending a notification to a specific user down to just pushing to a certain topic that is specific to the recipients UID.
Are there any downsides to using topics over firebase function observes when sending a push notification from user to user(s).
Topics are publicly accessible. So even if you create a topic for each user, all users can subscribe to each of those topics.
For that reason you should only use topics in this way, if the messages are consider public. E.g. in a public chat room scenario this would probably be fine, since everyone can already see the messages in the public chat room anyway. But sending private messages via a topic, means that other users can intercept them when they know the topic for a user.
If your messages are not meant to be public, you will need to send to the individual tokens. Your should only hit a rate limit in extreme cases. If that happens for you, reach out to Firebase support for personalized help in troubleshooting