Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

admin.messaging() is not a function while on "firebase-admin": "^11.3.0",

I’ve been trying to send a notfication to topic "All" and the console log shows error:

Notification sent failed: TypeError: admin.messaging is not a function

Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

// The Firebase Admin SDK to access Firestore.
var admin = require("firebase-admin/app");
const { applicationDefault } = require('firebase-admin/app');

admin.initializeApp({
  credential: applicationDefault(),
  databaseURL: "my-firebase-url"
});

exports.notificationsOnCreate = functions.database.ref("/{type}/{id}/").onCreate(async (snapshot, context) => {
  const payload = {
    notification: {
      title: 'cloud function demo',
      body: 'this is a test notification'
    }
  };
  
  try{
    return await admin.messaging().sendToTopic("All", payload)
    .then(function(response){
    console.log('Notification sent successfully: ', response);
    });
  } catch(err) {
    console.log('Notification sent failed: ', (err));
  }
})

Other stack overflow topics recommend updating firebase-admin to a version >5.1, but that seems to not be the issue here.

package.json file:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "16"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^11.3.0",
    "firebase-functions": "^4.1.0"
  },
  "devDependencies": {
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}

>Solution :

import from firebase-admin instead of firebase-admin/app

// The Firebase Admin SDK to access Firestore.
var admin = require("firebase-admin");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading