Error with Firebase on Electron app: Failed to load gRPC - firebase

I'm building an Electron app, and in the renderer.js file, I'm using Firebase Admin to get Firestore data. However, whenever I run it, it returns this error in the logs..
Error: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: electron-v2.0-darwin-x64-unknown
Found: [node-v48-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
I tried to run "npm rebuild", but it still didn't fix it.
I also tried updating Firebase Admin and gRPC.
Here is the code from the renderer.js file...
// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const admin = require('firebase-admin');
var serviceAccount = require('./credentials.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://mytestapp.firebaseio.com"
});
var db = admin.firestore();
const settings = {
timestampsInSnapshots: true
};
db.settings(settings);
function LoadList() {
db.collection("Orders").get().then(function(Collection){
Collection.forEach(function(OrderDoc){
console.log(OrderDoc.id)
})
}).catch(function(err){
console.error(err);
});
}
document.querySelector('#ListSec').addEventListener('click', LoadOrderList)
Any ideas? I've been trying to solve this for hours, but can't seem to figure it out.

That error message indicates that gRPC was installed for Node, not for Electron. Electron has a different binary interface, so binary modules like gRPC need to be installed specifically for Electron. You can generally do this just by running npm rebuild --runtime=electron --target=2.0.0 (modified to match the version of Electron you want to use).

The original answer by #murgatroid99 was helpful at the time, and a postinstall command worked great up until electron v7, where the issue returned.
For anyone else who comes across this issue, I've found a better solution:
the electron-rebuild package
npm install electron-rebuild --save-dev
Run it using
npx electron-rebuild
Or, add it as a postinstall command
{
...
"scripts": {
"postinstall": "electron-rebuild"
},
...
}
Further information is in the official Electron Documentation

Related

How to implement Firebase AppCheck inside firebase function to read Realtime database? [duplicate]

I recently enabled App Check for my firebase app and enforced it on both my cloud functions and database. The cloud function workflow is behaving correctly. However, I can no longer access the database from the function. A minimal version of my callable function looks something like this:
exports.myFunc = functions.https.onCall(async (data, context) => {
const adminApp = admin.initializeApp();
const ref = adminApp.database().ref('some-node');
if (context.app === undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.',
);
}
try {
return (await ref.orderByKey().equalTo('foo').get()).exists()
} catch(exc) {
console.error(exc);
}
});
This used to work before App Check, but now it fails and I see this in the logs:
#firebase/database: FIREBASE WARNING: Invalid appcheck token (https://my-project-default-rtdb.firebaseio.com/)
Error: Error: Client is offline.
Seems like I need to do something extra to get the admin app to pass App Check verification down to the database, but I haven't been able to find any documentation on this yet. I also tried using the app instance from functions.app.admin instead of initializing a new one, but this didn't help.
I have the latest version of the packages:
"firebase-admin": "^9.10.0"
"firebase-functions": "^3.14.1"
firebaser here
The behavior you're seeing is not how it's supposed to work, and we've been able to reproduce it. Thanks for the clear report, and sorry you encountered this.
If you (re)install the Firebase Admin SDK today, you won't be experiencing this same problem as we've fixed the problem in the #firebase/database dependency (in this PR).
If you're (still) experiencing the problem, you can check if you have the correct #firebase/database dependency by running:
npm ls #firebase/database
results look something like this:
temp-admin#1.0.0 /Users/you/repos/temp-admin
└─┬ firebase-admin#9.11.0
└── #firebase/database#0.10.8
If your #firebase/database version is lower than 0.10.8, you'll have to reinstall the Admin SDK, for example by deleting your node_modules directory and your package-lock.json file and running npm install again. This may also update other dependencies.

Firebase App Check not working with firebase functions - web project [duplicate]

I recently enabled App Check for my firebase app and enforced it on both my cloud functions and database. The cloud function workflow is behaving correctly. However, I can no longer access the database from the function. A minimal version of my callable function looks something like this:
exports.myFunc = functions.https.onCall(async (data, context) => {
const adminApp = admin.initializeApp();
const ref = adminApp.database().ref('some-node');
if (context.app === undefined) {
throw new functions.https.HttpsError(
'failed-precondition',
'The function must be called from an App Check verified app.',
);
}
try {
return (await ref.orderByKey().equalTo('foo').get()).exists()
} catch(exc) {
console.error(exc);
}
});
This used to work before App Check, but now it fails and I see this in the logs:
#firebase/database: FIREBASE WARNING: Invalid appcheck token (https://my-project-default-rtdb.firebaseio.com/)
Error: Error: Client is offline.
Seems like I need to do something extra to get the admin app to pass App Check verification down to the database, but I haven't been able to find any documentation on this yet. I also tried using the app instance from functions.app.admin instead of initializing a new one, but this didn't help.
I have the latest version of the packages:
"firebase-admin": "^9.10.0"
"firebase-functions": "^3.14.1"
firebaser here
The behavior you're seeing is not how it's supposed to work, and we've been able to reproduce it. Thanks for the clear report, and sorry you encountered this.
If you (re)install the Firebase Admin SDK today, you won't be experiencing this same problem as we've fixed the problem in the #firebase/database dependency (in this PR).
If you're (still) experiencing the problem, you can check if you have the correct #firebase/database dependency by running:
npm ls #firebase/database
results look something like this:
temp-admin#1.0.0 /Users/you/repos/temp-admin
└─┬ firebase-admin#9.11.0
└── #firebase/database#0.10.8
If your #firebase/database version is lower than 0.10.8, you'll have to reinstall the Admin SDK, for example by deleting your node_modules directory and your package-lock.json file and running npm install again. This may also update other dependencies.

Deploying Function Error on Cloud Function with error code 13 and Message "INTERNAL"

I'm deploying a Firestore trigger onCreate for my App, but everytime I want to deploy, it always Error
the console always showing Code 13 and Message "INTERNAL"
this is what comes up on Console
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog",
"status":{"code":13,"message":"INTERNAL"},
"authenticationInfo":{"principalEmail":"[My_EMAIL]"},
"requestMetadata":{"requestAttributes":{},"destinationAttributes":{}},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction",
"resourceName":"projects/etalase/locations/us-central1/functions/onNewMessage"}
this is my code on index.js
exports.onNewMessage = functions.firestore
.document('/messages/{groupChatId}/{groupChatId}/{messageFeedItem}')
.onCreate(async (snapshot, context) => {
const doc = snapshot.data();
console.log('------Message Created-----');
console.log(doc);
const idForm = doc.userID;
const idTo = doc.sellerID;
console.log('Message from : ', idForm);
console.log('Message to : ', idTo);
});
I expect this will deploy and every time a new message created on {messageFeedItem}, it will trigger the console, but even I can't deploy it
Thank you
So right now I can deploy the function by changing the directory
'messages/{groupChatId}/{groupChatId}/{messageFeedItem}'
into
'messages/{groupChatId}/{groupChatId2}/{messageFeedItem}'
my speculation is you can't have same name to the wildcard
You have to import firebase functions
import functions = require('firebase-functions');
or
const functions = require('firebase-functions');
If you did, then check your package.json
For anyone who got this far and still does not have a solution - here is what was wrong in my case
exports.fnName = functions.firestore
.document('Collection/{collId}/SubCollection/{subCollId')
.onUpdate((change, context) => {
...
});
Note the missing '} at the end of the document reference.
This caused the deploy to fail with the following on the client
Failed to configure trigger provider
And with the following in the function logs
"status":{
"code":13,
"message":"INTERNAL"
},
Set up Node.js and the Firebase CLI
In many cases, new features and bug fixes are available only with the
latest version of the Firebase CLI and the firebase-functions SDK.
It's a good practice to frequently update both the Firebase CLI and
the SDK with these commands inside the functions folder of your
Firebase project:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
my issue is because I use - character in my wild card
'chat/{abc-efg}'
I change - to _ and it works

Deploying firebase cloud function in typescript

I'm trying to deploy the very first cloud function.
It works perfectly fine, but when I try to deploy it in terminal, it sets out warning saying that "functions is declared but it's value is never read".
Is this some common starting mistake, as I am new to this subject? Thank you.
I tried both imports , deploy erros remains same
// const functions = require('firebase-functions');
import * as functions from 'firebase-functions'
Errors message
index.ts file code here
Your code doesn't declare any Cloud Functions yet, so eslint warns you that you're importing functions but not using it.
The message will disappear when you declare a Cloud Function in your index.js/index.ts. For example, the documentation on getting started contains this example:
exports.addMessage = functions.https.onRequest((req, res) => {
const original = req.query.text;
return admin.database().ref('/messages').push({original: original}).then((snapshot) => {
return res.redirect(303, snapshot.ref.toString());
});
});
As you can see, this code uses functions in its first line. So if you add this (or any other Cloud Functions declaration) to your code, you're using functions and eslint will no longer warn you about it not being used.
The error will disappear when you finally use "functions" in a cloud function.
nevermind, you are better off using
const functions = require('firebase-functions');
when importing firebase-functions in your index.js
========
EDIT : ======
Make sure that you have correctly installed those dependencies, by running those npm commands in the right folder:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools
Probably solved, but for me I was expecting ~/functions/index.ts to be the file building but the firebase cli added ~/functions/src/index.ts and THAT was the file.

Error parsing triggers Cannot find module when deploying firebase function

I am implementing a firebase function endpoint that requires I authenticate with two different projects. Information found on SO and other sources suggest this
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
const serviceAccountSource = require('./source.json');
const serviceAccountTarget = require('./target.json');
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert(serviceAccountSource)
})
const targetAdmin = admin.initializeApp({
credential: admin.credential.cert(serviceAccountTarget)
s}, "destination")
Where source.json and target.json are files storing the serviceAccount credentials (JSON) obtained from the Project Settings => Generate New Private Key.
My folder structure is as follows
functions/
index.ts
source.json
target.json
Running the following
npm run-script lint
produces no errors, however when I run
firebase deploy --only functions
I get
Error: Error parsing triggers: Cannot find module './source.json'
Firebase admin / functions versions as follows
"firebase-admin": "7.0.0",
"firebase-functions": "^2.2.0"
Typescript
"typescript": "^3.2.2"
Any ideas as what is causing the error.
If you are using Typescript try moving your source.json to the lib folder.
I found a solution to this. Although documentation on the firebase admin functions (parameters etc) seems to be very scarce I did notice that the credential.cert member takes a ServiceAccountPathOrObject.
I tried
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert('./source.json')
})
This failed with a path not found but this time it gave the path. From this I was able to see that there was a missing element in the Path
const sourceAdmin = admin.initializeApp({
credential: admin.credential.cert('./src/source.json')
})
The function deployed. I then tried to go back to the original code and added the 'src' folder to the path - however that resulted in the same error.
I prefer the above solution but I am still interested to know what caused the original error - given that much of the documentation out there seems to recommend this including this https://gist.github.com/brunobraga95/82bef0672ce451767107e62df1d8b28f - which is the code I am trying to implement.
The function has deployed and is working - so I can confirm the recommendation above works.

Resources