Skip to content
Advertisement

API sent Firebase notifications not received on device

I’m trying to send notifications based on business logic that runs (on nodejs) on my server via a cron.

Issue

Notifications aren’t appearing on the device.

Description

I’m using the firebase admin node package.

My code looks something like this

import admin from "firebase-admin";

import serviceAccount from "../../firebase-admin.json" assert { type: 'json' };
import { getMessaging } from 'firebase-admin/messaging';

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

...

console.log(message);
await getMessaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
     console.log('Error sending message:', error);
  });

My log output is something like this

{
  notification: {
    title: 'This is a string',
    body: 'This is another string'
  },
  token: 'aLphaNumeric:reallyLongAlphaNumericWithDashesAndUnderscores'
}
Successfully sent message: projects/<project-name>/messages/<id>

Everything I’m seeing suggests this should be sent!

Advertisement

Answer

sendMulticast and the Admin FCM APIs allow you to multicast a message to a list of device registration tokens. You can specify up to 500 device registration tokens per invocation.

sendMulticast take 2 arguments as input, 1st one is notification which contains the title and body of the message. The other argument is fcmTokens with type array, so you must pass that argument as array even though there is only one fcmToken

//Import the file where you have imported the service file.
const adminApp = require("../firebase/firebaseConfig");
const notificationToAll = (title, body, tokens) => {
var notibody = {
  notification: {
    title: title,
    body: body,
  },
  tokens: tokens,
};
return new Promise((resolve, reject) => {
  adminApp
    .messaging()
    .sendMulticast(notibody)
    .then((response) => {
      console.log(response.responses);
      if (response.responses[0].error != undefined) {
        console.log(JSON.stringify(response.responses[0].error));
      }
      resolve(response);
    })
    .catch((error) => {
      console.log(JSON.stringify(error));
      reject(error);
    });
});
};

module.exports = notificationToAll;

app.js

const notificationToAll = require("./helper/notification");
notificationToAll(
  "This is a string",
  `This is another string`,
  ["aLphaNumeric:reallyLongAlphaNumericWithDashesAndUnderscores"]
)

This is tested code and working in a live environment.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement