Search code examples
javascriptfirebasereact-nativepush-notificationfirebase-cloud-messaging

Mobile apps can't receive notification


I'm using fcm to send notification to Android, iOS and the web. It is working for the web, but not for the mobile apps.

Here's my code:

// backend

const firebase = require("firebase-admin");
const { getMessaging } = require("firebase-admin/messaging");
const serviceAccountKey = require('./firebase-config.json')

const projectId = "PROJECT ID HERE"; // i'm replacing it with the real projectid

firebase.initializeApp({
  credential: firebase.credential.cert(serviceAccountKey),
  databaseURL: `https://${projectId}.firebaseio.com`
});


const sendNotification = async (user, tokens) => {
  const message = {
    data: {
      title: "Test Message",
      body: JSON.stringify({
        content: `this is a test message`,
        username: user.name,
        userId: user._id
      }),
    },
    tokens,
  };
  try {
    const res = await getMessaging().sendMulticast(message)
    console.log('successfully send message')
    console.log(res)
  } catch (error) {
    const code = error?.errorInfo?.code;
    console.log("Error sending message:", code);
    console.log("error", error);
    }
  };
}

Here when I log the result it says the message/notification was send successfully but I don't get the notification on mobile apps. I do get it on the web. I'm using react native for the mobile apps. (i'm using react-native for mobile app)

and when I try to use the test cloud message feature from firebase dashboard the opposite happens I get notification on mobile app but not on web.

Here's the code for the web

/firebase-messaging-sw.js

self.addEventListener("push", (event) => {
  const data = event.data.json()?.data;
  const body = JSON.parse(data.body);
  console.log(url);
  const options = {
    body: body.content,
    icon: "/logo.png",
  };

  event.waitUntil(self.registration.showNotification(data.title, options));
});

Solution

  • Try updating the key of message object. Change 'data' to 'notification'.

    const sendNotification = async (user, tokens) => {
    const message = {
        data: { //Update this to notification
          title: "Test Message",
          body: JSON.stringify({
            content: `this is a test message`,
            username: user.name,
            userId: user._id
          }),
        },
        tokens,
      };
      try {
        const res = await getMessaging().sendMulticast(message)
        console.log('successfully send message')
        console.log(res)
      } catch (error) {
        const code = error?.errorInfo?.code;
        console.log("Error sending message:", code);
        console.log("error", error);
        }
      };
    }