1

I'm trying to send a push notification through Firebase/Node JS. I currently have this code running on Heroku.

var Firebase = require('firebase');
var request = require('request');
var express = require('express');
var FCM = require('fcm-node');
var app = express();

app.set('port', (process.env.PORT || 5000));

app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/push', function(request, response) {
  response.send("running");
});

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});

// Planet Firebase API Key
var API_KEY = "AIz..."; // found at Project Settings > General > Web API Key
var fcm = new FCM(API_KEY);

var config = {
  apiKey: "AIz...",
  authDomain: "XXX.firebaseapp.com", // Authentication > Sign-In Method > OAuth Redirect Domains
  databaseURL: "https://XXX.firebaseio.com/", // Database > Url at the top
  storageBucket: "gs://XXX.appspot.com", // Storage > Url at the top
};
var firebase = Firebase.initializeApp(config);
var ref = firebase.database().ref();

function listenForNotificationRequests() {
  var requests = ref.child('notifications');
  requests.on('child_changed', function(requestSnapshot) {
        var objectAdded = requestSnapshot.val();
        var uid = receiver["uid"]
        var notificationMessage = objectAdded["message"]
        sendNotificationToUser(uid, notificationMessage);
  }, function(error) {
        console.error(error);
  });
};

function sendNotificationToUser(receiverID, notificationMessage) {
    var message = { 
        to: '/notifications/'+receiverID,       
        notification: {
            title: "App Title", 
            body: notificationMessage,
            badge: 1
        }
    };

    fcm.send(message, function(err, response){
        if (response) {
            console.log("Successfully sent with response: ", response);
        } else {
            console.log("Something has gone wrong! Error: " + err);
        }
    });
}

// start listening
listenForNotificationRequests();

Whenever fcm.send() is called, I get back:

Something has gone wrong! Error: NotAuthorizedError

This leads be to believe Firebase isn't initializing correctly, but I've checked the links and keys multiple times. What have I done incorrectly?

AL.
  • 33,241
  • 9
  • 119
  • 257
user1072264
  • 121
  • 2
  • 11

1 Answers1

4

In your code, I noticed this part (specially the comment):

// Planet Firebase API Key
var API_KEY = "AIz..."; // found at Project Settings > General > Web API Key
var fcm = new FCM(API_KEY);

You're probably receiving an 401 - Authentication Error.

When using FCM, you should always use the Server Key and not the Web API Key.
This is also visible in the Firebase Console: Project Settings > Cloud Messaging > Server Key.

See my answer here for an idea about the different keys.

Community
  • 1
  • 1
AL.
  • 33,241
  • 9
  • 119
  • 257