-
Couldn't load subscription status.
- Fork 3.9k
How can I send a Cloud Messaging notification with Cloud Functions? #923
-
I'm having some trouble doing so. Can someone please help?
PS ~ Please show both JS and TS samples.
Thanks.
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 2 comments 2 replies
-
Hi @shauryaaher, here's a sample: https://github.com/firebase/functions-samples/tree/main/fcm-notifications
And here are the docs: https://firebase.google.com/docs/cloud-messaging/send-message
Beta Was this translation helpful? Give feedback.
All reactions
-
Hey @shauryaaher Please describe your question
Do you want to send notification to specific users or to users who subscribed to some topic or to all of your users?
In case if you want to send to a specific user you will have to get fcm token for that user and use it while sending the notification
Example:
const message = snap.data();
const payload = {
notification: {
title: "New message",
body: message.type == "text" ? message.data :
"Click here to see the message",
sound: "default",
android_channel_id: "messages",
},
data: {
"type": "chat",
},
};
console.log(`type: ${message.type}, message data: ${message.data}`);
admin.messaging().sendToDevice(
message.fcm_token,
payload,
{
timeToLive: 86400,
priority: "high",
},
Beta Was this translation helpful? Give feedback.
All reactions
-
I'd like to send notifications to users who don't use my site very often so that I don't lose user retention.
Beta Was this translation helpful? Give feedback.
All reactions
-
I suggest that you should store the fcm_token of all users in your database and using analytics check which user not came back in maybe 7 days and the send him the notification using this fcm_token.
You can also do one thing that maintain a last_visit field in users document and whenever user loads your site check if that user is logged in or not and if that user is logged in then update it's document by changing the last_visit field in users document. Use this field to to send notification to thoes users who doesn't visited your site in some time period. All this can be done in Firebase Functions.
Beta Was this translation helpful? Give feedback.