Deploying firebase cloud function fails when I initialise firebase with a service account key - node.js

so very recently I started using google's firebase cloud functions, and loved it immediately! I very quickly restructured a project I was going to work on, and included firebase in it, so I could use the cool features of firestore, in combination with cloud functions.
Up until today, everything went on smoothly; pretty much, until I decided to play with google's FCM (Firebase Cloud Messaging) to send notifications via node js. Before this, I had created some really dense functions and already deployed to my console which were working seamlessly.
The tricky part is, at the time I created and deployed these functions, I initialised my firebase app in node js with admin.initalizeApp().
With this, everything worked fine(both locally & deployed) until I tried to use admin.messaging().sendToDevice... which resulted in a very nasty error, that basically told me I couldnt send notifications if I wasnt authenticated..
The 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. See https://firebase.google.com/docs/admin/setup for setup instructions. Raw server response: "<HTML>
> <HEAD>
> <TITLE>Unauthorized</TITLE>
> </HEAD>
> <BODY BGCOLOR="#FFFFFF" TEXT="#000000">
> <H1>Unauthorized</H1>
> <H2>Error 401</H2>
> </BODY>
> </HTML>
> ". Status code: 401.)
Following the error, I used a few tips from some other users on stack overflow who had faced this error, and most of them suggested that I download a service key from my console, and initialise my firebase app with admin.initializeApp({credential:admin.credential.cert(serviceAccount)})
This solution worked beautifully, as it allowed me to test my notification without seeing the above error ever again.
However, when all my tests were done, and I was ready to deploy, the new function I had just created to work on notification, as well as all my previously deployed functions could not get deployed. All of a sudden, the old working functions in my console had a red exclamation mark beside them, and I had to get rid of them. Even after I cleared out all of my console and tried to redeploy all my functions, it failed, and failed and failed with no errors(context: I wasted the whole day!!! lool!) Every tip on the internet failed for me, until I reverted back to my old way of initialising my firebase app admin.initializeApp(), then booom! all my functions uploaded successfully, and then again, the authentication error appeared again when I tried to retest my notification function.....
I guess my question is: is there anything I don't know about deploying functions to the firebase console with my app initialised with a service account key I downloaded from my console?
Is there something else I need to do to get my functions to deploy properly every time I init my firebase admin app with a service account key?? Because initialising the app with just .initalizeApp() works fine for all other purposes both locally and when deployed, except when using FCM. Can anyone please help with what is happening here??

I think it can be solved by initializing two apps and using them as objects described here. One with credentials that work for other functions and one for messaging.
If you need it only for one function you can do it even inside it. I have tested it like this:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
exports.first_app = functions.https.onRequest(async (req, res) => {
res.json(admin.app().name);
})
exports.other_app = functions.https.onRequest(async (req, res) => {
var otherApp = admin.initializeApp({
credential: **<< different credential here >>**
}, "2nd_app");
res.json(otherApp.name);
})

as already mentioned, you should initialize a second app just for the new function you are creating. You should put the initialization code inside the new function like this
export const saveMap = functions.https.onRequest(async (req, response) => {
const serviceAccount = require("./../serviceAccountKey.json");
admin.initializeApp({
projectId: "serviceAccount.project_id",
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://your_project_id_here.firebaseio.com", //update this
storageBucket: "your_bucket_name_here.appspot.com" //update this
}, "2nd_app")
I had the same issue and once I put the second initialization code into the new function, it worked. Note that in this code the serviceAccountKey.json is in the same folder as src and lib.

Related

Firebase Functions: Error: Client is offline

I just recently started using Firebase functions for the first time. When I was using Firebase Functions for Firestore, it worked fine but after I switched to Realtime, I've consistently been getting "Error: Client is offline".
It happens when I turn on node.js and run my application for the first time, and I .get() some data from the realtime database.
When I click on the respective line at which the error exists, it shows me this.
This is how I initialized firebase-admin:
admin.initializeApp({
projectId: <project id>,
storageBucket: <bucket url>,
credential: admin.credential.cert(serviceAccount),
databaseURL: <db url>,
});
Is it because I have the FIREBASE_CONFIG and GCLOUD PROJECT environment variables are missing error? I've seen a lot of different posts that other people are getting the same issue, but I haven't come across a proper solution.
If anyone has any solutions or if you need more information, please let me know!
I have a feeling you may be hitting a race condition in the JavaScript implementation of get(). If that is the case, you can work around it by using the once() method, which should work exactly the same in this scenario:
const _dataSnapshot = await admin.database().ref('users').child(req.body.user_uid).once();
...

when i use firebase.database().goOnline(); I get an error

this is my code
admin.initializeApp({...});
var db = admin.database();
let ref = db.ref(...);
await ref.once("value",function () {...},);
firebase.database().goOffline();
firebase.database().goOnline();
ref.on("value",function () {...},);
);
when i use firebase.database().goOnline(); I get an error
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at app
You're mixing two ways of addressing Firebase.
You can access Firebase through:
Its client-side JavaScript SDK, in which case the entry point is usually called firebase.
Its server-side Node.js SDK, in which case the entry point is usually called admin.
Now you initialize admin, but then try to access firebase.database(). And since you did call admin.initializeApp that's where the error comes from.
My guess is that you're looking for admin.database().goOnline() or db.goOnline().
Also note that there is no reason to toggle goOffline()/goOnline() in the way you do now, and you're typically better off letting Firebase manage that on its own.

Google Firebase Web App - Error involving Cloud Functions and Firestore

Recently, I tried to follow a few demos online to get started on a Google Firebase Cloud Functions Node.js server-side code for an application. Upon attempting to add a Firebase App (and Firestore with it),
const functions = require('firebase-functions');
const firebase = require('firebase-admin');
require('firebase/firestore');
var serviceAccount = require("<private key>.json");
const initAppFirebase = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "<URL>"
});
var db = firebase.firestore();
I begin to get this one error that mentions a missing "annotations.proto" file from the google-gax module (which is apparently imported at some point in Firestore).
Error during trigger parsing: Error occurred while parsing your function
triggers.
Error: The include `google\api\annotations.proto` was not found.
at Function.GoogleProtoFilesRoot._findIncludePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:312:11)
at GoogleProtoFilesRoot.resolvePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:298:31)
...
at v1beta1 (C:\...\functions\node_modules\#google-
cloud\firestore\src\v1beta1\index.js:30:10)
at new Firestore (C:\...\functions\node_modules\#google-
cloud\firestore\src\index.js:229:18)
I have looked around on the internet, but nobody else seems to have this problem. I just reinstalled the files, but I am still getting this issue. Removing the Firestore and Firebase initializeApp code allows it to work, so I believe it has something to do with that.
Here are my module versions from package.json
"firebase-admin": "^5.12.0",
"firebase-functions": "^1.0.1",
"firestore": "^1.1.6",
Is there a way to fix this problem (botched installation, outdated libraries, missing code/requires etc.)? Thank you very much.
EDIT: Added code and package.json for version info. I dug around in the actual file \node_modules\google-gax\lib\grpc.js and found that it tries to return a valid path leading to the import file annotation.proto by trying to test google\api\annotations.proto at each parent directory.
var current = originPath;
var found = fs.existsSync(path.join(current, includePath));
while (!found && current.length > 0) {
current = current.substring(0, current.lastIndexOf(path.sep));
found = fs.existsSync(path.join(current, includePath));
}
if (!found) {
throw new Error('The include `' + includePath + '` was not found.');
}
return path.join(current, includePath);
There is, unfortunately, no such directory, though perhaps it is looking for the annotations file in google-proto-files\google\api\annotations.proto (but adding that file in manually leads to further errors). There is also a github issue here https://github.com/googleapis/nodejs-firestore/issues/175 mentioning it.
You say that you're trying to build a web app. But the code you are using is for initializing the Firebase Admin SDK in a (server-side) Node.js script.
If you want to use Firestore in your web app, start with the code you see when you click the WEB tab on this page:
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-firestore.js"></script>
And then:
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
You can get the values in that initializeApp call by:
Going to the Project overview page
Click ADD ANOTHER APP
Click Add Firebase to your web app

Firebase Node.js admin SDK timeouts when trying to access Realtime DB

Using the Node.js admin SDK with Firebase Functions I get a timeout whenever I try to access the Realtime Database. This occurs only when testing a function locally (firebase serve --only functions,hosting) and when the default app is initialized using the functions.config().firebase.
This is a new behavior that started just a couple a days ago. However, if I try to initialize the default app with the serviceAccount.json file everything works as expected.
I'm using firebase-admin version 4.2.1 and firebase-functions version 0.5.9.
I wrote a straight forward http triggered function that fails due to timeout:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.database();
exports.testDbConnection = functions.https.onRequest((req, res) => {
return admin.database().ref().once('value')
.then(function(snapshot) {
res.json(snapshot);
}).catch(function(error) {
res.json(error);
});
});
from the documentation
Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system
see https://firebase.google.com/docs/functions/http-events#terminate_http_functions
This might depend on the firebase-tools version that you are using, but looks familiar to this Github issue
The solution for it is to either upgrade to the latest version of the CLI or use the workaround solution:
Go to https://cloud.google.com/console/iam-admin/serviceaccounts
Click “Create service account”, give it a name (e.g. emulator), give it the Project>Owner role.Check “Furnish a new private key”, pick “JSON”.
Save the file somewhere on your computer
Run export GOOGLE_APPLICATION_CREDENTIALS="absolute/path/to/file.json"
Run firebase serve --only functions

No longer captures the event from firebase by Admin SDK

I have installed and run firebase admin on my node server, it has been running well until today, there is no given error to tell what happened, it simply stops working.
var admin = require("firebase-admin");
var serviceAccount = require("mycom-firebase-adminsdk-d1ebt123456.json");
var app = FireBaseAdapter.admin.initializeApp({
credential: FireBaseAdapter.admin.credential.cert(serviceAccount),
databaseURL: "https://xxxx.firebaseio.com"
});
var db = app.database();
var ref = db.ref("messages"); // this node actually exists in my db.
ref.on("value", function(snapshot) {
// this will never be called - which has been working before.
console.log(snapshot.val());
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
I even wrap it in the try catch to print out the error, but there isn't any. I can log into the firebase console in the account and see my database with no change (small database) (although it seems be slower than normal).
Is there something wrong with firebase Admin SDK? Any help is appreciated.
After spending many hours to find out the cause, I found the problem.
Since I couldn't find any way to enable log of firebase-admin, so it was the dead end to troubleshoot the issue while everything runs silently, so I switched to use the firebase package to have the logging
var firebase = require("firebase");
firebase.initializeApp({
databaseURL: "https://xxxxx.firebaseio.com",
serviceAccount: '....'
});
firebase.database.enableLogging(true); // <=== important
My issue is quite similar to this question
then I could see the actual error:
p:0: Failed to get token: Error: Error refreshing access token:
invalid_grant (Invalid JWT: Token must be a short-lived token and in a
reasonable timeframe)
The solution for this issue was explained on this anwser. This issue caused by a poor synchronisation of the computer's clock where the code was executed that had a lag of 5 minutes (due to a faulty battery for the internal clock).
It started working again when I manually changed the internal time of my computer to the correct one (or totally I reset my computer date-time).
In my case, after resetting the datetime&timezone, the firebase automatically works again and I do not need to re-generate another service account.

Resources