4

I want to add the push notification thing using FCM in Node.js .For that I tried this

and this and also this

My nodejs code

var FCM = require('fcm-node');

var serverkey = 'SERVERKEY';  
var fcm = new FCM(serverkey);
var message = {  
   to : req.body.userToken,
   collapse_key : 'XXX',
   data : {
     my_key: 'my value', contents: "abcv/"
   },
   notification : {
     title : 'Title of the notification',
     body : 'Body of the notification'
   }
 };

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

Whenever I try to run this code and start my server,I get this error in the console always.

 /var/www/html/chatApp/node_modules/fcm-node/lib/fcm.js:10
 function FCM(accountKey, proxy_url=null) {
                              ^
 SyntaxError: Unexpected token =
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/var/www/html/chatApp/node_modules/fcm-node/index.js:1:80)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)

Can anybody please explain what I'm doing wrong?

Neha
  • 389
  • 4
  • 8
  • 24

2 Answers2

15

I used the firebase-admin package for sending the notifications (https://firebase.google.com/docs/cloud-messaging/admin/send-messages)

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

var serviceAccount = require("./firebase-adminSDK.json");

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
});
const messaging = admin.messaging()
    var payload = {
        notification: {
            title: "This is a Notification",
            body: "This is the body of the notification message."
        },
        topic: 'topic'
        };


    messaging.send(payload)
    .then((result) => {
        console.log(result)
    })

The firebase-adminSDK.json can be download following the steps in https://firebase.google.com/docs/admin/setup#add_firebase_to_your_app

This code will send a notification to the topic 'topic', however, the firebase-admin package allows sending notifications to a specific device.

Pedro Silva
  • 2,655
  • 1
  • 15
  • 24
  • how did you handle the secret and private keys inside the json file? did you use a process environment variable? – Fiehra Sep 08 '22 at 22:10
  • This was 4 years ago, I don't remember sorry :( – Pedro Silva Nov 08 '22 at 12:03
  • 1
    well you can save it in env and then fetch it, only private key is going to show some error, to solve use this const pkey = process.env.private_key.replace(/\\n/g, '\n'); Just remove the extra 'n' from private key before passing it to admin.initializeApp() @Fiehra – SAURABH Feb 24 '23 at 06:42
1

I have shared the way to integrate fcm notification using the env file to keep your private key secret. I have used this library to send this https://www.npmjs.com/package/firebase-admin

Code below is to send notification to single or to multiple user, you just have to pass token in an array.

import * as admin from 'firebase-admin';

import config from '../config/default';


const pkey = process.env.private_key.replace(/\\n/g, '\n');

const creden = {
type: 'service_account',
project_id: process.env.PROJECT_ID,
private_key_id: pkey,
private_key: process.env.PRIVATE_KEY,
client_email: process.env.CLIENT_EMAIL,
client_id: process.env.CLIENT_ID,
auth_uri: process.env.AUTH_URI,
token_uri: process.env.TOKEN_URI,
auth_provider_x509_cert_url: process.env.AUTH_PROVIDER_CERT_URL,
client_x509_cert_url: process.env.CLIENT_CERT_URL
}

const credentialObject:object = creden;

admin.initializeApp({
credential: admin.credential.cert(credentialObject)
});
 
export default admin;

//this code in different file, function to send notification

  import admin from '../config/firebase-config';
  export default async function fcmSend(notification:any, registrationTokens: any, extraData:any) {

if(!extraData){
    extraData = null 
}   
 
let returnData = null;

try {

    registrationTokens = _.uniq(registrationTokens);

    if(registrationTokens.length === 0) {
        console.log("Empty token");
        return
    } 
 let message = {
        notification: notification,
        "android": {
            "notification": {
                "sound": "default"
            }
        },
        "apns": {
            "payload": {
                "aps": {
                    "sound": "default"
                }
            }
        },
        tokens: registrationTokens,
        data: {
            ...notification,
            icon:''
        },
        "webpush": {
            "headers": {
                "Urgency": "high"
            }
        }
    }

    const messaging =  admin.messaging();
    await messaging.sendMulticast(message)
        .then((response) => {
            //console.log(response);
            
            if (response.failureCount > 0) {
                const failedTokens:any = [];
                response.responses.forEach((resp, idx) => {
                    if (!resp.success) {
                        failedTokens.push(registrationTokens[idx])
                    }
                });
                console.log('List of tokens that caused failures: ' + failedTokens)
                returnData = failedTokens
                return failedTokens
            }
            returnData = response;
        }).catch(e =>{
            console.log(e);
            
        });

            } catch (e) {
    returnData = false;
    console.log(e);
}
return returnData;
 }
SAURABH
  • 71
  • 6