In order to send push notifications at scale to your Android apps (FCM can also be used to send notifications to web browsers or iOS devices), you need to either set up your own backend or use a service.
If you want to save time and concentrate on building your business logic, you can integrate SendMan to take care of this for you.
If not, this guide will walk you through sending notifications using Node.js.
Before we can start, you should have a service account JSON file and a database URL from the firebase console. If you don’t have them, you can read more about creating them in this guide.
Installation
The recommended way to use FCM, according to Firebase’s documentation, is using their Admin SDK. Let’s install it:
1npm install -S firebase-admin
Initialization
We now need to initialize the Admin SDK.
We’ll use the database URL and the path to the service account JSON file that we downloaded from Firebase.
1const admin = require("firebase-admin");2const serviceAccount = require("path/to/service-account-key.json");34admin.initializeApp({5 credential: admin.credential.cert(serviceAccount),6 databaseURL: "https://sendman-blog-example.firebaseio.com"7});
Replace the databaseURL
with your own url.
Sending Notifications
Now that we have the SDK initialized, sending notifications can easily be done as follows:
1const registrationTokens = [2 'YOUR_REGISTRATION_TOKEN_1',3 // …4 'YOUR_REGISTRATION_TOKEN_N',5];67const message = {8 notification: {9 title: 'Push notifications are great!',10 body: 'They could be better if you used SendMan :-)'11 }12};1314console.log(`Attempting to send the notification to ${registrationTokens.length} devices.`);1516try {17 const { failureCount, successCount } = await admin.messaging().sendToDevice(registrationToken, message, { priority: 'high' });18 console.log(`Successfully sent the notification to ${successCount} devices (${failureCount} failed).`);19} catch (err) {20 console.log('An error occurred while connecting to Firebase');21}
This is an example of sending a notification message (as opposed to data messages, which are usually used for pushing data to apps without displaying anything to the user).
Notification messages are usually sent with a “high” priority so that they are more likely to be displayed by the mobile operating system (you can read more about advanced messaging options here).
The code example above sends a notification to multiple devices, described by an array of tokens (alternatively, a single string can be used).
You have now implemented FCM push notification in Node.js!