0

I'm trying to implement FCM push notifications in a react.js app using Firebase Realtime Database Cloud functions, for the first time and stuck at this:

error: Message must be a non-null object

I've read some answers that provide on this topic but non of them helped me. I don't know what is exactly wrong with my code. Here's my index.js inside the functions directory.

const functions = require('firebase-functions');
const admin = require("firebase-admin");
admin.initializeApp();
    exports.observeFollow = functions.database
  .ref('/notifications/{userEmail}/{uid}')
  .onCreate(async (snapshot, context) => {
    const userEmail = context.params.userEmail;
    const uid = context.params.uid;
    const notificationData = snapshot.val();

    console.log("📥 New Notification:", notificationData);

    console.log('📥 Sender Name:', notificationData.senderName);

    // Get the user who was followed (should be under /users/{userEmail})
    const userRef = admin.database().ref(userEmail);
    const userSnap = await userRef.once('value');

    if (!userSnap.exists()) {
      console.error('❌ User not found for: ${userEmail}');
      return null;
    }

    const followedUser = userSnap.val();
    const fcmToken = followedUser.fcmToken;

    console.log('FCMTOKEN------:' + fcmToken);

    console.log('followedUser Data------:' + followedUser);

    if (!fcmToken || fcmToken.length < 100) {
      console.warn('⚠️ Invalid FCM token for user ${userEmail}:', fcmToken);
      return null;
    }

    const payload = {
      notification: {
        title: 'You have a new connection!',
        body: 'Wayne wants to connect.',
      }
    };

//     const message = {
//   token: fcmToken,
//   notification: {
//     title: "You have a new connection!",
//     body:  'Wayne wants to connect.';
//   }
// };

    try {
      const response = await admin.messaging().send(fcmToken, payload);
      console.log('✅ Message sent:', response);
    } catch (error) {
      console.error('❌ Error sending FCM:', error);
    }

    return null;
  });

Firebase Function Logs: enter image description here

2
  • 2
    According to the API documentation for send(), it doesn't take arguments called "fcmToken" and "payload". Maybe review that documentation and try again with what you learn there. Commented 23 hours ago
  • Check your device token. May be device token is empty or null Commented 14 hours ago

2 Answers 2

0

As Doug commented, the send method doesn't takes a single parameter with both the message and the token in there.

Based on that documentation for send and the examples in the documentation on building send requests:

const payload = {
  token: fcmToken,
  notification: {
    title: "You have a new connection!",
    body:  'Wayne wants to connect.';
  }
};

try {
  const response = await admin.messaging().send(payload);
  console.log('✅ Message sent:', response);
} catch (error) {
  console.error('❌ Error sending FCM:', error);
}
1
0

I was able to fix the issue, for anyone who ran into this issue. Here's my solution.

const payload = {
    notification: {
        title: "You have a new Connect",
        body: senderName + " Wants to connect with you.",
    },
    apns: {
        payload: {
            aps: {
                sound: "default",
                badge: 1,
            }
        }
    },
    token: fcmToken,
};

try {
  const response = await admin.messaging().send(payload);
  console.log('✅ Message sent:', response);
} catch (error) {
  console.error('❌ Error sending FCM:', error);
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.