im using node js for my backend and frontend react native expo, im trying to work with FCM but when i try to send notification with my backend this error shows up :
FirebaseMessagingError: An error occurred when trying to authenticate to the FCM servers. Make sure the credential used to authenticate this SDK has the proper permissions
this is my code
const admin = require("firebase-admin");
const serviceAccount = require("../serviceaccountkey.json");
const User = require('../models/user');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
/**
* Send a push notification to a user identified by their userId.
* @param {string} userId - The user's ID to send the notification to.
* @param {string} message - The message content of the notification.
* @returns {Promise<string>} - Promise resolving to the notification ID if successful.
*/
async function sendPushNotification(userId, message) {
try {
// Fetch user's FCM token
const userFCMToken = await getUserFCMToken(userId);
if (userFCMToken) {
// Construct payload for FCM message
const payload = {
notification: {
title: "New Message",
body: message.toString(),
},
};
// Send FCM message
const response = await admin.messaging().sendToDevice(userFCMToken, payload);
console.log("Notification sent successfully:", response);
return response.messageId; // Return notification ID or status
} else {
console.error(`User with ID ${userId} does not have a registered FCM token.`);
return null;
}
} catch (error) {
console.error("Error sending push notification:", error);
throw error; // Throw error for handling in caller function
}
}
/**
* Fetches the Firebase Cloud Messaging (FCM) token for a user.
* @param {string} userId - The ID of the user to fetch the FCM token for.
* @returns {Promise<string|null>} - Promise resolving to the user's FCM token or null if not found.
*/
async function getUserFCMToken(userId) {
try {
// Fetch user data from the database based on userId
const user = await User.findById(userId);
if (!user) {
console.error(`User with ID ${userId} not found.`);
return null;
}
// Extract FCM token from user data
const fcmToken = user.pushToken;
if (!fcmToken) {
console.error(`User with ID ${userId} does not have a registered FCM token.`);
return null;
}
return fcmToken;
} catch (error) {
console.error('Error fetching FCM token:', error);
throw error; // Throw error for handling in caller function
}
}
module.exports = { sendPushNotification };
i already did the http v1 but cant enable the cloud messaging because it aint on the google console library. when i try to use the expo notification tool it works.
SEL SUS is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.