I am testing out the Firebase Cloud Messaging function in my React app which was bootstrapped with create-react-app. Note that I have already intialized firebase (including admin SDK on server-side) properly and my client side is deployed on https. What I did so far was to:
- Initialize firebase messaging in firebase.js, and also request for notification permission and listen out for onMessage event
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(() => {
console.log("Permission granted!");
})
.catch(() => {
console.log("Permission denied!");
});
messaging.onMessage(payload => {
console.log("onMessage: ", payload);
});
- Create service worker file firebase-messaging-sw.js in public directory
importScripts("https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js");
var config = {
messagingSenderId: <messageID hidden>
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
- I read from another Stackoverflow post that with create-react-app post that this was also necessary to include in index.js
if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("../firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration.scope);
})
.catch(function(err) {
console.log("Service worker registration failed, error:", err);
});
}
- To test out the messaging easily, I added a button in Main.js that will send to my server the token on click (and then the server will proceed to send the message)
const handlePushButtonClick = () => {
messaging.getToken().then(token => {
axios.post(<Server link hidden>, {
token
});
});
};
- I then set up the necessary route in my express server like this
app.post("/api/push", async (req, res) => {
const registrationToken = req.body.token;
var message = {
data: {
score: "850",
time: "2:45"
},
token: registrationToken
};
fb.admin
.messaging()
.send(message)
.then(response => {
console.log("Successfully sent message:", response);
res.sendStatus(200);
})
.catch(error => {
console.log("Error sending message:", error);
});
});
Here's the issue, I have verified that my server is successfully receiving the token and in fact has successfully sent the message but on my client-side, I am not receiving the onMessage payload object at all.
Recall from my code that what I expect to receive on my client side dev console is a console.log with onMessage and the payload.
messaging.onMessage(payload => {
console.log("onMessage: ", payload);
});