Firebase notification admin.messaging() is not a function - Firebase cloud messaging - node.js

Here is my code
var admin = require("firebase-admin");
var serviceAccount = require("./google-services.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
module.exports.admin = admin
My API file code
const admin = require('../firebaseConfig')
async function sendFireBaseNotification(registrationToken , message ){
const options = notification_options
return admin.messaging().sendToDevice(registrationToken, message, options)
.then( response => {
console.log("Notification sent successfully"+response)
})
.catch( error => {
console.log(error);
});
}
my firebase version "firebase-admin": "^5.13.1"
I am getting error 'TypeError: admin.messaging is not a function'
I am looking for the solutions , please help.

Version 5.13.1 of the Firebase Admin SDK that you're using is from July 2018 (!). I recommend upgrading to a more recent version.

Related

Error trying to authenticate with FCM servers when sending message using Firebase Admin SDK in node.js

When I try to send to send an FCM notification to a topic I get the following error...
Error: An error occurred when trying to authenticate to the FCM
servers. Make sure the credential used to authenticate this SDK has
the proper permissions.
I am using a brand new generated service account key and pointing to it correctly. I have confirmed that the path to the key is correct. I have also enabled Cloud Messaging for the project.
const { messaging } = require('firebase-admin');
var admin = require('firebase-admin');
console.log(process.cwd());
async function run() {
try {
var serviceAccount = require("/Users/myUser/src/my_project/node_admin/my_project-5617a-firebase-adminsdk-lwpk6-5dad9000e0.json");
const topic = 'all';
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
const payload = {
notification: {
title: "Test1234",
body: "body",
sound: 'test-sound.wav'
}
};
var options = {
priority: "high"
}
await admin.messaging().sendToTopic(topic , payload , options);
} catch (e) {
console.log(e);
}
}
run();
Hello i was copy code and run --> it working
so i think you can check path of file auth json
var serviceAccount = require("/Users/myUser/src/my_project/node_admin/my_project-5617a-firebase-adminsdk-lwpk6-5dad9000e0.json");
good luck!

DB.collection is not a function in firebase?

I am trying to connect to firebase realtime database (not firestore) but I get the error that db.collection is not a function. Other answers in StackOverflow are mentioned with respect to Firestore. Thanks for your help.
const admin = require('firebase-admin');
// Firebase configuration - this should not be public.
// Please use your own config if you intend to use this code.
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxx",
}
// Initialize Firebase
admin.initializeApp(firebaseConfig)
const db = admin.database();
console.log("Database setup");
(async () => {
try {
let query = db.collection('users');
console.log("Doing database query now");
await query.get().then(querySnapshot => {
console.log(querySnapshot);
});
} catch (error) {
console.log(error);
}
})();
const db = admin.database() is an instance of Firebase realtime database and not Firestore. To get an instance of Firestore, use admin.firestore().
const admin = require('firebase-admin');
admin.initializeApp(/* service account */)
const db = admin.firestore();
console.log("Firestore setup");
Admin SDK uses a service account and not the same public credentials. You can refer to the documentation for detailed information. You can get a service account from project settings.
Do note that if you are using Cloud functions then you can leave initializeApp() empty.

Why message id from Firebase Cloud Messaging is empty

I am migrating from legacy HTTP to v1 using the NPM firebase-admin module. But I have the problem that when sending the notification it doesn't give any error, but it doesn't return the message-id and the notification is not received on the device.
Node version: 12.14.1.
firebase-admin version: 9.6.0
Server code:
const admin = require('firebase-admin');
var serviceAccount = require('./file.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
const messaging = admin.messaging();
async function sendPush() {
const message2 = {
notification: {
title: 'test title',
body: 'test'
},
token: 'valid-token'
};
try {
const test = await messaging.send(message2);
console.log('--------------------------Successfully sent message:--------------------------');
console.log(test);
console.log('------------------------------------------------------------------------------');
} catch(err) {
// Will catch both thrown exceptions as well as rejections
console.log('--------------------------Error sending message:', err);
}
}
When I send a notification using the sendPush function, I receive the following response in the console:
--------------------------Successfully sent message:--------------------------
projects/project-name/messages/
------------------------------------------------------------------------------
It does not contain the message-id specified in the docs and I am not receiving the notification.
Docs sample response:
projects/myproject-b5ae1/messages/0:1500415314455276%31bd1c9631bd1c96
Edit:
I tested the sendToDevice function (Legacy API) from firebase-admin and it works.
messaging.sendToDevice('valid-token', message)
.then(response => {
console.log('--------------------------Successfully sent message:--------------------------');
console.log(response);
console.log('------------------------------------------------------------------------------');
})
.catch(err => {
console.log('--------------------------Error sending message:', err);
});
The push is delivered. But send, sendMulticast and sendAll (v1 API) still not working.
Solved.
The problem was that the token coming from android was not correct for the new FCM versions. After updating the token generation in the apps, it has started to work with both legacy and v1.

app.auth(...).signInWithCredential is not a function firebase error

I'm trying to add google login to my node js firebase app. I'm getting the following error:
app.auth(...).signInWithCredential is not a function
Here's the code on the server
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
return app.auth().signInWithCredential(credential);
On the client
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
var unsubscribe = app.auth().onAuthStateChanged((firebaseUser) => {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(googleUser.getAuthResponse().id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch( (error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
console.dir(errorMessage);
}).then( (success) => {
console.dir(success);
var id_token = googleUser.getAuthResponse().id_token;
axios.post('/auth/google-login', {
id_token: id_token
}).then(response => {
var result = response.data;
if (result.status === "ok") {
this.setState({complete: true});
} else if (result.error) {
this.setState({error: result.error});
}
}).catch(error => {
console.dir(error);
this.setState({error: "error"});
});
});
});
What I'm I doing wrong?
At the top of the nodejs file, I have
var app = require('./base');
where base :
var serviceAccount = require("./service-account-file.json");
const app = fadmin.initializeApp({
credential: fadmin.credential.cert(serviceAccount),
databaseURL: "https://test.firebaseio.com"
});
module.exports = app;
Hi there are hints that the problem starts with node version 6.21. that
app.auth().signInWithCredential(credential)
Don't work
It works in v6.2.0.
Try signInWithEmailAndPassword
Use latest version of node
The function signInWithCredential is part of the Firebase JavaScript SDK
The Firebase JavaScript SDK implements the client-side libraries used by applications using Firebase services.
The Firebase Admin SDK is intended to run on a server or other privileged environment. The Admin SDK does not include sign-in functions.

Firebase function not responding to Pub/Sub message

I feel like I might be missing something simple, but I can't get a Cloud Function for Firebase to respond to a Pub/Sub published message. It works fine when I deploy using cloud and opt for the Admin SDK for Node.js, but Auth is tricky; it works for the first write and then it fails to authenticate.
With the release of Cloud Function for Firebase, I decided to try again. My function code is as follows:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
function pushOrderToFirebase(completedOrder) {
admin.initializeApp(functions.config().firebase);
//setters and getters for the message that will be pushed to firebase
admin.database().ref('/orders').push({
name: curDriverName,
recipient: recipient,
address: address,
details: details,
isDelivered: isDelivered,
failureReason: failureReason,
time: formattedTime
}).then(snapshot => {
console.log(snapshot);
});
}
exports.firebasePusherAlpha = functions.pubsub.topic('test-topic').onPublish(event => {
const pubSubMessage = event.data;
let parsedMessage = null;
try {
parsedMessage = pubSubMessage.json;
console.log(parsedMessage);
} catch (e) {
console.error('PubSub message was not JSON', e);
}
pushOrderToFirebase(parsedMessage);
callback();
});
Unfortunately, it doesn't get called when I publish a pubsub message.

Resources