With the latest update of firebase cloud functions, I am getting errors while initializing app, as well as database ref.
First Error:
Following should work based on Firebase functions v1.0 documentation and samples ( https://github.com/firebase/friendlychat-web/blob/master/cloud-functions/functions/index.js )
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(); //this fails
I get following error on firebase deploy for above code:
Error: Error occurred while parsing your function triggers.
Error: Failed to parse app options file: Error: ENOENT: no such file or directory, open '[object Object]'
at FirebaseAppError.FirebaseError [as constructor] (/Users/ZZZ/dummy/functions/node_modules/firebase-admin/lib/utils/error.js:39:28)
at FirebaseAppError.PrefixedFirebaseError [as constructor] (/Users/ZZZ/dummy/functions/node_modules/firebase-admin/lib/utils/error.js:85:28)
at new FirebaseAppError (/Users/ZZZ/dummy/functions/node_modules/firebase-admin/lib/utils/error.js:119:28)
at FirebaseNamespaceInternals.loadOptionsFromEnvVar (/Users/ZZZ/dummy/functions/node_modules/firebase-admin/lib/firebase-namespace.js:214:19)
at FirebaseNamespaceInternals.initializeApp (/Users/ZZZ/dummy/functions/node_modules/firebase-admin/lib/firebase-namespace.js:64:28)
at FirebaseNamespace.initializeApp (/Users/ZZZ/dummy/functions/node_modules/firebase-admin/lib/firebase-namespace.js:362:30)
at Object.<anonymous> (/Users/ZZZ/dummy/functions/index.js:5:7)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
This error is resolved if I pass the config file (but it goes against the firebase documentation)
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var config = {
apiKey: "<APIKEY>",
authDomain: "<DOMAIN>",
databaseURL: "<URL>",
projectId: "<PROJECTID>",
storageBucket: "<BUCKET>",
messagingSenderId: "<ID>"
};
admin.initializeApp(config);//this works
Second Error:When I make database ref call as below , it fails and gives error:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
var config = {
apiKey: "<APIKEY>",
authDomain: "<DOMAIN>",
databaseURL: "<URL>",
projectId: "<PROJECTID>",
storageBucket: "<BUCKET>",
messagingSenderId: "<ID>"
};
const app = admin.initializeApp(config);
exports.updateUserProfile = functions.database.ref('/UserProfile/{userid}')
.onCreate((snapshot, context) => {
console.log(snapshot.val());
});
Logs:
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint /Users/ZZZ/dummy/functions
> eslint .
✔ functions: Finished running predeploy script.
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
Error: Unexpected token o in JSON at position 1
You are experiencing this error because of a bug in firebase CLI version 3.18.1.
Try uninstalling the current version and install 3.18.0 and this should solve the error.
npm uninstall -g firebase-tools
npm install -g firebase-tools#3.18.0
UPDATE:
Firebase CLI version 3.18.2 has been released and the issue is now resolved.
I was experiencing this same error. For me the problem appears to have been resolved when I followed these instructions to migrate from a Javascript project to a Typescript project.
It was a bit of a hail mary and might not actually be what fixed it. Still, if you're still stuck it won't hurt to do a quick backup and give it a shot.
If you've updated the NPM modules, then you are now using the Stable release of Cloud functions v1. There are some minor changes that should be done to your existing code. Please follow the guide below
https://firebase.google.com/docs/functions/beta-v1-diff?utm_source=email&utm_medium=email&utm_campaign=cloud_functions_v1.0
Version 1.0.0 of the Firebase SDK for Cloud Functions introduces some
important changes in the API. The primary change, a replacement of
event.data format with data and context parameters, affects all
asynchronous (non-HTTP) functions. The updated SDK can also be used
with firebase-functions-test, a brand new unit testing companion SDK.
See Unit Testing Functions for more information.
Related
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
I'm creating an app that uses firebase-functions. I created my app directory and ran firebase init. After that was completed I tried to run the hello world program that it gives you using firebase serve, and I get this error:
TypeError: _onRequestWithOpts is not a function
at Object.httpsProvider._onRequestWithOpts
from what it looks like, it seems to be an issue with the onRequest() method but I have made apps using this before and have never ran into this issue. I literally didn't change a single piece of code that they initially give you so unless they decided to change something overnight i'm not sure what the issue is.
using firebase deploy works, but firebase serve does not. Using express and adding new functions, the error pops up when running firebase deploy and serve.
const functions = require('firebase-functions');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-
functions
//
exports.helloWorld = functions.https.onRequest((request, response)
=> {
response.send("Hello from Firebase!");
});
Gabriels-MacBook-Pro:functions Mike$ firebase serve
=== Serving from '/Users/Gabe/Desktop/mycart-functions'...
⚠ Your requested "node" version "8" doesn't match your global
version "10"
✔ functions: Emulator started at http://localhost:5000
i functions: Watching "/Users/Gabe/Desktop/mycart-
functions/functions" for Cloud Functions...
⚠ TypeError: _onRequestWithOpts is not a function
at Object.httpsProvider._onRequestWithOpts
(/usr/local/lib/node_modules/firebase-
tools/lib/emulator/functionsEmulatorRuntime.js:278:24)
at Object.httpsProvider.onRequest
(/usr/local/lib/node_modules/firebase-
tools/lib/emulator/functionsEmulatorRuntime.js:283:34)
at Object.<anonymous> (/Users/Gabe/Desktop/mycart-
functions/functions/index.js:6:39)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js
(internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
⚠ We were unable to load your functions code. (see above)
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.
I already have some firebase cloud functions that runs fine, and now I try to add SendGrid functionality to one of the functions as described in https://youtu.be/JVy0JpCOuNI. The firebase CLI won't run my code because it says it has a TypeError
The code is written in Typescript and the transpiler doesn't give any error. I am using the latest versions of the CLI and the SDK.
admin.initializeApp();
const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
const SENDGRID_API_KEY = firebaseConfig.sendgrid.key;
const sgMail = require(‘#sendgrid/mail’);
sgMail.setApiKey(SENDGRID_API_KEY);
I have checked that the firebase config contains the sendgrid key:
$ firebase functions:config:get
{
"sendgrid": {
"key": "MY_SEND_GRID_KEY"
}
}
I get this output when I try to deploy --only functions:
functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory. :warning: functions: Error from emulator. Error occurred while parsing your function triggers.
TypeError: Cannot read property ‘key’ of undefined
It is this line that has the error:
const SENDGRID_API_KEY = firebaseConfig.sendgrid.key;
What can I change so I don't get this error?
The variables that you set using the CLI via firebase functions:config:get don't end up in process.env.FIREBASE_CONFIG. They end up in functions.config().
import * as functions from 'firebase-functions'
const key = functions.config().sendgrid.key
FIREBASE_CONFIG just determines how the admin SDK should be initialized with no parameters passed to admin.initializeApp().
Please read the documentation for more information.
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