I am trying to deploy a scheduled cloud function and while deploying i am getting the error as :-
HTTP Error: 400, The request has errors
Functions deploy had errors with the following functions:
scheduledFunction
To try redeploying those functions, run:
firebase deploy --only functions:scheduledFunction
To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.schedulefunction = functions.pubsub.schedule('every 5 minutes').onRun(async context => {console.log('running every 5 minutes');});
I don't understand how to call HTTPS functions in local.
I made index.js file and exported hello functions and run firebase functions:shell.
I read this document, and I followed this way:
https://firebase.google.com/docs/functions/local-shell#invoke_https_functions
# invoke
myHttpsFunction()
myHttpsFunction.get()
myHttpsFunction.post()
but I got this message hello is not defined
This is index.js I wrote.
const admin = require('firebase-admin')
const {https} = require('firebase-functions')
admin.initializeApp()
exports.hello = https.onRequest((_, response) => {
response.end('hello')
})
This is terminal.
$ firebase functions:shell
✔ functions: Using node#8 from host.
✔ functions: Emulator started at http://localhost:5001
i functions: Watching "/Users/xxx/xxx" for Cloud Functions...
⚠ Default "firebase-admin" instance created!
i functions: HTTP trigger initialized at http://localhost:5001/xxx/us-central1/hello
i functions: HTTP trigger initialized at http://localhost:5001/xxx/us-central1/callable
firebase > ⚠ Default "firebase-admin" instance created!
firebase > hello()
ReferenceError: hello is not defined
> firebase > hello() should be return hello, but hello is not defined.
This is a bug in the Firebase CLI emulator. Please follow the issue on GitHub. For now, follow this advice in that issue.
In the future, post bug reports there as well. There is not much Stack Overflow can help you with in regards to bug reports.
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 trying to setup a Firebase project on Codeship CI/CD and I cannot seem to get the service credentials JSON key to work with my project when it's stored in an environment variable.
MVCE
Dev environment startup script
export FIREBASE_CREDENTIAL=BASE64ENCODED_credentials_json
export DATABASE_URL=https://my-project.firebaseio.com
echo $FIREBASE_CREDENTIAL | base64 -D > FIREBASE_CREDENTIAL.json
npm start
index.ts
import * as admin from "firebase-admin";
const credentials = require("../FIREBASE_CREDENTIAL.json");
const databaseURL = process.env.DATABASE_URL;
console.log(credentials.project_id); // succeeds
console.log(databaseURL); // is correct
admin.initializeApp({
...credentials,
databaseURL,
databaseAuthVariableOverride: { uid: "scraper" }
});
admin
.database()
.ref("/test")
.set(admin.database.ServerValue.TIMESTAMP);
Codeship script
echo $FIREBASE_CREDENTIAL | base64 -di > FIREBASE_CREDENTIAL.json
nvm install 8
npm install
npm test
Results
On dev machine, the write succeeds as expected
On Codeship CI container, I get this error.
console.warn node_modules/#firebase/logger/dist/index.cjs.js:66
[2018-10-05T12:53:51.316Z] #firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"Failed to parse access token response: Error: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND\"."}
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.