I'm using a Node.js server to send topic notifications to Android devices using FCM. I tested the topic notifications from Firebase console and it did work, so the problem seems to be on the server side.
Here is my implementation:
**firebase/fb.js**
const admin = require("firebase-admin");
//Firestore Connect
const DATABASE_NAME = "....";
var serviceAccount = require('../config/.....json');
module.exports = admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
**notifications.js**
const router = express.Router();
const fb = require('../firebase/fb');
const db = fb.firestore();
const fcm = fb.messaging();
var topic = `/topics/${req.params.topic.toString()}`;
var currentTime = new Date().getTime();
var payload = {
notification: {
title: req.body.title,
body: req.body.body
}
};
var options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
fcm.sendToTopic(topic, payload, options)
.then((response) => {
res.send(200, req.body);
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
res.send(400, error);
console.log('Error sending message:', error);
});
});
When I execute this code I get the following response:
Successfully sent message: { messageId: 7218165350026662000 }
The notification is not displayed on the Android phone. The device is registered to the specific topic.
I have also tried to use the `.send(message)` method but the result was the same. Moreover, I'm using quite the same algorithm to send to a specific device and that works.
What's wrong with my code?