Firebase web push notification with NodeJS not working

Viewed 3333

I'm building an app that sends web push notifications using firebase and a NodeJs server but I'm getting a 'mismatched-credential' error, how can I fix this?

I'm first generating a json file that 'generate private key' button from the console gave me , and adding the admin SDK to my app, from my server code, this way

var admin = require("firebase-admin");

var serviceAccount = require("path/to/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://nodeproject-2bc3o.firebaseio.com"
});

Then I'm building the send request

// This registration token comes from the client FCM SDKs.
var registrationToken = 'YOUR_REGISTRATION_TOKEN';

var message = {
  data: {
    score: '850',
    time: '2:45'
  },
  token: registrationToken
};

// Send a message to the device corresponding to the provided
// registration token.
admin.messaging().send(message)
  .then((response) => {
    // Response is a message ID string.
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.log('Error sending message:', error);
  });

The docs says that // This registration token comes from the client FCM SDKs so I'm using the token I got from the client as my registrationToken, which I retrieved the following way , from my client javascript code , and then sent to the server

messaging.getToken().then((currentToken) => {
  if (currentToken) {
    sendTokenToServer(currentToken);
    updateUIForPushEnabled(currentToken);
  }

Finally, after sending a message from the server, using the token , I get the following error

  errorInfo: {
    code: 'messaging/mismatched-credential',
    message: 'SenderId mismatch'
  },
  codePrefix: 'messaging'
}

Which is the correct way to retrieve the client token , send it to the server , and then use it to send a push notification to the client? Or what I'm I doing wrong?

1 Answers

If you use Firebase Cloud Functions as backend server then the serviceAccountKey.json is not necessary and more simple.

See https://firebase.google.com/docs/functions/get-started#import-the-required-modules-and-initialize-an-app

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access Cloud Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

These lines load the firebase-functions and firebase-admin modules, and initialize an admin app instance from which Cloud Firestore changes can be made.

And, fcm sample is https://github.com/firebase/functions-samples/tree/master/fcm-notifications

Related