javascriptfirebasegoogle-cloud-functionsfirebase-cloud-messagingfirebase-admin

FCM push notification error: code: 'messaging/invalid-payload


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


Solution

  • 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);
    }