This tutorial aims to introduce you to Firebase Cloud Messaging (FCM), a cross-platform messaging solution that lets you reliably deliver messages at no cost. We'll get you up and running by setting up FCM in a project, sending a first notification, and handling these notifications in an application.
By the end of this tutorial, you'll be able to:
For this tutorial, you should have:
Before you can send or receive messages, you need to set up FCM in your project. This involves creating a Firebase project, adding a Firebase configuration file, and initializing Firebase in your app.
Once you've set up FCM, you can send your first notification. This involves creating a message, setting the target, and sending the message.
When a notification is received, your app needs to handle it. This can involve displaying the notification, updating the UI, or even performing a background task.
// Import the firebase module
const firebase = require("firebase");
// Initialize Firebase
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
projectId: "<PROJECT_ID>",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
// Define a message
var message = {
data: {
score: '850',
time: '2:45',
},
topic: 'general',
};
// 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);
});
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
In this tutorial, we went over setting up Firebase Cloud Messaging in your project, sending your first notification, and handling incoming notifications. The next steps would be to delve deeper into the capabilities of FCM, such as topic messaging, subscription management, and message targeting.
Create a Firebase project and set up FCM. Send a test notification to a specific topic.
Write a function to handle incoming FCM notifications and log the payload to the console.
Expand your function from Exercise 2 to display a notification to the user when a message is received.
The solution to this exercise involves following the setup steps outlined in section 2.1 and the message sending steps in section 3.2.
The solution to this exercise involves creating a function that uses the onMessage()
method from the Firebase Messaging instance.
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
The solution to this exercise involves expanding the function from Exercise 2 to create a notification. The exact implementation will vary depending on your application's UI library or framework.