I am trying to create a Cloud function which sends a firebase cloud message to the users when a new document is created. Somehow I can not deploy the function to Firebase.
Here is my index.js:
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp(functions.config().firebase);
exports.sendAll = functions.region("europe-west3").firestore
.document("NewsCard/{docId}")
.onCreate((snapshot) => {
const title = snapshot.get("Title");
const subject = snapshot.get("Text");
const payload = {
notification: {
title: title,
body: subject,
sound: "default",
},
};
return admin.messaging().sendToTopic("Announcement", payload);
});
This is the error I get when I type firebase deploy:
✔ functions: Finished running predeploy script.
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (64.26 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 12 function sendAll(europe-west3)...
⚠ functions[sendAll(europe-west3)]: Deployment error.
...
Error: Functions did not deploy properly.
What is causing this problem? I read somewhere on the internet, that the firestore path .document("NewsCard/{docId}") could be wrong. But I dont know what to use instead.
Here is my Firestore:
Figured it out myself. Seems to be a problem with Node. See #3120 for more information. Downgrade Node to 14 helps.
Related
I was looking to test a function but getting this error. Am I missing anything? Can anyone help me?
This is the error message in my terminal:
firebase deploy --only functions
=== Deploying to 'procuradoria-15967'...
i deploying functions
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i functions: ensuring required API artifactregistry.googleapis.com is enabled...
+ functions: required API artifactregistry.googleapis.com is enabled
+ functions: required API cloudfunctions.googleapis.com is enabled
+ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (52.22 KB) for uploading
+ functions: functions folder uploaded successfully
i functions: updating Node.js 12 function testeadm(us-central1)...
Functions deploy had errors with the following functions:
testeadm(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
This is my Index.js:
// Initialize Cloud Firestore through Firebase
const { initializeApp } = require("firebase-admin/app")
const { getFirestore } = require("firebase-admin/firestore")
const functions = require('firebase-functions');
const { GoogleSpreadsheet } = require('google-spreadsheet');
initializeApp();
exports.testeadm = functions.https.onRequest(async(req, res) => {
console.log("teste")
const doc = new GoogleSpreadsheet("...")
await doc.useServiceAccountAuth({"private_key": "...",
"client_email": "..."});
await doc.loadInfo();
console.log(doc.title)
})
This is the register Firebase log error message:
testeadm
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"Function failed on loading user code. This is likely due to a bug in the user code. Error message: Error: please examine your function logs to see the error cause: https://cloud.google.com/functions/docs/monitoring/logging#viewing_logs. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging. Please visit https://cloud.google.com/functions/docs/troubleshooting for in-depth troubleshooting documentation."},"authenticationInfo":{"principalEmail":"..."},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.UpdateFunction","resourceName":"projects/.../locations/us-central1/functions/testeadm"}
I have a fresh project but was looking to test scheduled functions. Am I missing anything?
$ firebase deploy
=== Deploying to 'testing-db'...
i deploying functions
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
! functions: missing required API cloudbuild.googleapis.com. Enabling now...
+ functions: required API cloudfunctions.googleapis.com is enabled
+ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (24.45 KB) for uploading
i functions: ensuring required API pubsub.googleapis.com is enabled...
i functions: ensuring required API cloudscheduler.googleapis.com is enabled...
! functions: missing required API cloudscheduler.googleapis.com. Enabling now...
+ functions: required API pubsub.googleapis.com is enabled
+ functions: required API cloudscheduler.googleapis.com is enabled
+ functions: functions folder uploaded successfully
i functions: creating Node.js 14 function scheduledFunction(us-central1)...
Functions deploy had errors with the following functions:
scheduledFunction(us-central1)
i functions: cleaning up build files...
Error: There was an error deploying functions
Index.js
const functions = require('firebase-functions');
exports.scheduledFunction = functions.pubsub
.schedule('every 1 minutes')
.onRun((context) => {
return console.log('This will be run every 1 minutes!');
});
Firebase log shows:
Error: Failed to upsert schedule function scheduledFunction in region europe-west1
I ran into this issue as well, but the solution was not region related like #Priyashree's answer. Rather, when I ran firebase deploy --only functions --debug the logs revealed that my scheduler had an error.
The bottom of the log had this error:
Error: Failed to upsert schedule function foo in region us-central1
But scrolling up a bit revealed:
<<< HTTP RESPONSE BODY {"error":{"code":400,"message":"Schedule or time zone is invalid.","status":"INVALID_ARGUMENT"}}
I had a typo in my function schedule:
functions.pubsub.schedule("every 1 minute").onRun((context) => {}
every 1 minute should have been every 1 minutes. Note the missing 's'.
In general, I think it's useful to enable '--debug' on the firebase deploy command so you can see detailed log output of the exact error.
When you are using scheduled functions in Firebase Functions, an App Engine instance is created that is needed for Cloud Scheduler to work. You can read about it here.They use the location that has been set by default for resources. I think that you are getting that error because there is a difference between the default GCP resource location you specified and the region of your scheduled cloud function. If you click on the cogwheel next to project-overview in Firebase you can see where your resources are located.
Check your Cloud Scheduler function details and see which region it has been deployed to. By default, functions run in the us-central1 region. Check this link to see how we can change the region of the function.
I am using Cloud Build to deploy my firebase project (hosting and cloud functions) trigged by a commit to a branch in a github repo. The deploy is successful and the site works, but the cloud functions don't run after the deploy. They don't even show up in the log as being called, so there are no errors.
I click a button from the UI that calls a cloud function, which saves some data to the real-time database. The code to call the function is run in a try catch, and the catch code runs. The logs for the cloud function show nothing -- the function isn't even run. When I then deploy the project locally from my laptop instead of via cloud build, the cloud function runs when the button is clicked and the data is saved to the database and the logs indicate that the function was invoked. None of the cloud functions are invoked when triggering an event from the front end, however, when I have deployed from Cloud Build
It's only when the project is deployed by Cloud Build that the functions don't run when they are called. I am wondering if this could be a permissions issue?
Front end code:
const createTeam = (payload) => {
return async (dispatch, getState, getFirebase) => {
debugger;
const createTeam = getFirebase().functions().httpsCallable("createTeam");
console.log("create team===>", createTeam);
try {
console.log("about to run");
await createTeam(payload);
dispatch(
sendNotification({
severity: "success",
message: "Team Created",
isOpen: true,
})
);
} catch (e) {
dispatch(
sendNotification({
severity: "error",
message: "An error occurred and team was not created.",
isOpen: true,
})
);
}
};
};
Build file:
steps:
- name: "gcr.io/cloud-builders/npm"
dir: "functions"
args: ["install"]
# Install
- name: "gcr.io/cloud-builders/npm"
args: ["install"]
# Build
- name: "gcr.io/cloud-builders/npm"
args: ["run", "build"]
# Deploy
- name: "gcr.io/$PROJECT_ID/firebase"
args: ["deploy", "--project=$PROJECT_ID"]
from the deployment logs:
Hosting URL: xxxx
Project Console: xxxx
✔ Deploy complete!
✔ hosting[agile-boost]: release complete
i hosting[agile-boost]: releasing new version...
✔ hosting[agile-boost]: version finalized
i hosting[agile-boost]: finalizing version...
✔ functions[launchAssessments(us-central1)]: Successful update operation.
✔ functions[createTeam(us-central1)]: Successful update operation.
✔ functions[sendParticipantEmailWhenAssessmentOpens(us-central1)]: Successful update operation.
✔ functions[completeAssessments(us-central1)]: Successful update operation.
✔ functions[refreshMetricCategoryAvg(us-central1)]: Successful update operation.
✔ functions[saveParticipantAnswer(us-central1)]: Successful update operation.
✔ functions[updateParticipant(us-central1)]: Successful update operation.
✔ functions[closeAssessmentsWhenTeamIsDeleted(us-central1)]: Successful update operation.
✔ functions[getParticipantsData(us-central1)]: Successful update operation.
✔ functions[createAccount(us-central1)]: Successful update operation.
✔ functions[addParticipantToAssessment(us-central1)]: Successful update operation.
✔ functions[createAssessment(us-central1)]: Successful update operation.
✔ functions[reviseAssessmentMetrics(us-central1)]: Successful update operation.
✔ functions[refreshMetricQuestionAvg(us-central1)]: Successful update operation.
✔ functions[updateParticipantWhenTeamParticipantUpdates(us-central1)]: Successful update operation.
✔ functions[refreshMetricTagAvg(us-central1)]: Successful update operation.
✔ functions[updateMetricsWhenParticipantStatusChanges(us-central1)]: Successful update operation.
✔ functions[addNewTeamParticipantToActiveAssessments(us-central1)]: Successful update operation.
✔ functions[getSurveyData(us-central1)]: Successful update operation.
i functions: scheduler job firebase-schedule-completeAssessments-us-central1 is up to date, no changes required
i functions: scheduler job firebase-schedule-launchAssessments-us-central1 is up to date, no changes required
✔ pubsub: required API pubsub.googleapis.com is enabled
✔ scheduler: required API cloudscheduler.googleapis.com is enabled
i pubsub: ensuring required API pubsub.googleapis.com is enabled...
i scheduler: ensuring required API cloudscheduler.googleapis.com is enabled...
i functions: updating Node.js 10 function completeAssessments(us-central1)...
i functions: updating Node.js 10 function launchAssessments(us-central1)...
i functions: updating Node.js 10 function getParticipantData(us-central1)...
i functions: updating Node.js 10 function getParticipantsData(us-central1)...
i functions: updating Node.js 10 function closeAssessmentsWhenTeamIsDeleted(us-central1)...
i functions: updating Node.js 10 function updateParticipantWhenTeamParticipantUpdates(us-central1)...
i functions: updating Node.js 10 function updateMetricsWhenParticipantStatusChanges(us-central1)...
i functions: updating Node.js 10 function sendParticipantEmailWhenAssessmentOpens(us-central1)...
i functions: updating Node.js 10 function addNewTeamParticipantToActiveAssessments(us-central1)...
i functions: updating Node.js 10 function saveParticipantAnswer(us-central1)...
i functions: updating Node.js 10 function getSurveyData(us-central1)...
i functions: updating Node.js 10 function updateParticipant(us-central1)...
i functions: updating Node.js 10 function addParticipantToAssessment(us-central1)...
i functions: updating Node.js 10 function createAssessment(us-central1)...
i functions: updating Node.js 10 function createTeam(us-central1)...
i functions: updating Node.js 10 function createAccount(us-central1)...
i functions: updating Node.js 10 function reviseAssessmentMetrics(us-central1)...
i functions: updating Node.js 10 function refreshMetricQuestionAvg(us-central1)...
i functions: updating Node.js 10 function refreshMetricTagAvg(us-central1)...
i functions: updating Node.js 10 function refreshMetricCategoryAvg(us-central1)...
✔ database: rules for database xxxx released successfully
i database: releasing rules...
✔ hosting[agile-boost]: file upload complete
i hosting: uploading new files [4/6] (66%)
i hosting: hashing files [34/35] (97%)
i hosting: hashing files [34/35] (97%)
i hosting[agile-boost]: found 35 files in build
i hosting[agile-boost]: beginning deploy...
✔ functions: functions folder uploaded successfully
i functions: packaged functions (52.61 KB) for uploading
i functions: preparing functions directory for uploading...
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
✔ database: rules syntax for database agile-boost is valid
i database: checking rules syntax...
✔ functions: Finished running predeploy script.
> tsc
> functions# build /workspace/functions
Running command: npm --prefix "$RESOURCE_DIR" run build
> tslint --project tsconfig.json
> functions# lint /workspace/functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
i deploying database, functions, hosting
=== Deploying to 'xxxx'...
gcr.io/agile-boost/firebase:latest
Status: Downloaded newer image for gcr.io/agile-boost/firebase:latest
Digest: sha256:063a10dfecc2b3bb4245316fb89ae1588f594bb8bb6e950ecf6a9488015e20bb
38ee9b020816: Pull complete
ddf8c3713c7d: Pull complete
9819791ca1ba: Pull complete
19c9987a828c: Pull complete
40ba0f817ab5: Pull complete
8cdf70a16731: Pull complete
9819791ca1ba: Download complete
9819791ca1ba: Verifying Checksum
8cdf70a16731: Download complete
8cdf70a16731: Verifying Checksum
38ee9b020816: Download complete
38ee9b020816: Verifying Checksum
ddf8c3713c7d: Download complete
ddf8c3713c7d: Verifying Checksum
40ba0f817ab5: Download complete
40ba0f817ab5: Verifying Checksum
19c9987a828c: Download complete
19c9987a828c: Verifying Checksum
38ee9b020816: Waiting
ddf8c3713c7d: Waiting
9819791ca1ba: Waiting
38ee9b020816: Pulling fs layer
ddf8c3713c7d: Pulling fs layer
9819791ca1ba: Pulling fs layer
19c9987a828c: Pulling fs layer
40ba0f817ab5: Pulling fs layer
8cdf70a16731: Pulling fs layer
e5c5821cd889: Already exists
55abbc6cc158: Already exists
8439168fd8dc: Already exists
c159512f4cc2: Already exists
1b49aa113642: Already exists
4f250268ed6a: Already exists
latest: Pulling from agile-boost/firebase
Using default tag: latest
Pulling image: gcr.io/agile-boost/firebase
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 am creating my first firebase function app and I was going/following through this tutorial/repo
So what I did was in my main file Index.js (inside functions folder)
const app = express();
const functions = require("firebase-functions");
const authRoutes = require("./src/routes/auth.js");
const meetupRoutes = require("./src/routes/meetup.js");
const eventbriteRoutes = require("./src/routes/eventbrite.js");
const nonMiddleWareRoutes = require("./src/routes/nonMiddleware.js");
app.use("/", nonMiddleWareRoutes);
app.use("/auth", authRoutes);
app.use("/meetup", meetupRoutes);
app.use("/eventbrite", eventbriteRoutes);
const api = functions.https.onRequest(app);
module.exports = {
api
};
now moving back to the root folder we have firebase.json which just contains this
{}
and .firebaserc
{
"projects": {
"default": "functions-firebase-2312"
}
}
Now, Whenever I do firebase deploy, it logs this in terminal
=== Deploying to 'functions-firebase-2312'...
i deploying functions
i functions: ensuring necessary APIs are enabled...
✔ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i functions: packaged functions (60.3 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 8 function api(us-central1)...
✔ functions[api(us-central1)]: Successful update operation.
✔ Deploy complete!
Please note that it can take up to 30 seconds for your updated functions to propagate.
Project Console: https://console.firebase.google.com/project/functions-firebase-2312/overview
but does not give me the url for the function.
Any idea what I could be doing wrong?
You will be given a URL the first time you deploy a function. After that, you can go to the Firebase console to see the URL in the Functions dashboard. They appear in rather small letters.