Firebase Function not giving Function URL - firebase

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.

Related

Deployment Error deploying Cloud Function with Firebase Trigger

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.

How Can I call HTTPS function with 'firebase functions:shell'?

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.

Firebase-tools is not uploading newly created functions to Firebase

I am working on an Angular project and I am writing Firebase functions that I would like to deploy to Firebase. As I write more functions for Firebase and try to deploy them to Firebase using firebase deploy --only functions, only existing functions get deployed. More specifically, I have 16 functions that I would like to deploy to Firebase but only the same 12 get deployed.
So far, I have done the following to try to fix the problem:
I made sure that I am on the latest firebase-tools (6.7.0)
I have tried specifying the newly written functions I would like to deploy using firebase deploy --only functions:<NEW FUNCTION NAME HERE>
Remove all export functions from the functions/src/index.ts file and upload a blank index.ts. Even when using a blank index.ts file, the same functions still get deployed to Firebase.
I know there can be up to a 30-second delay when uploading functions to Firebase, so I have even waited for an entire night before trying to upload new functions.
I have started from complete scratch using firebase init to recreate the whole functions directory and it still keeps uploading the same functions.
I upgraded from the free Firebase plan to the Spark plan.
The following code is the main index.ts file which is located in functions/src/index.ts.
import * as functions from 'firebase-functions';
import { firestore } from 'firebase-admin';
import * as moment from 'moment';
import { request } from 'https';
// Local Functions Imports
import * as Permissions from './permissions';
import * as Groups from './groups';
import * as Shifts from './shifts';
import * as Roles from './roles';
import * as Session from './sessions';
import * as Users from './users';
import * as Slack from './slack';
import * as ScheduleChanges from './schedule-changes';
import * as Email from './email';
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
/* -------- USER MANAGEMENT -------------- */
export const createUser = Users.createUser;
export const addUserToDefaultJoinGroups = Users.addUserToDefaultJoinGroups;
export const deleteUser = Users.deleteUser;
/* -------- SESSION MANAGEMENT -------------- */
export const addSessionID = Session.addSessionID;
/* -------- ROLE MANAGEMENT -------------- */
export const addRoleID = Roles.addRoleID;
export const removeAllShiftsAssociatedWithRole = Roles.removeAllShiftsAssociatedWithRole;
/* -------- SHIFT MANAGEMENT -------------- */
export const addShiftID = Shifts.addShiftID;
export const hourly_job = Shifts.hourly_job;
export const changeShiftStatsTest = Shifts.changeShiftStatsTest;
/* -------- GROUPS MANAGEMENT -------------- */
export const addGroupID = Groups.addGroupID;
export const addGroupIDNewTestFunction = Groups.addGroupIDNewTestFunction;
/* -------- PERMISSIONS MANAGEMENT -------------- */
export const addPermissionID = Permissions.addPermissionID;
/* -------- Emailing -------------- */
export const sendWelcomeEmailToNewUser = Email.sendWelcomeEmailToNewUser;
export const sendWelcomeEmailToNewUser2 = Email.sendWelcomeEmailToNewUser2;
/* -------- SLACK MESSAGING MANAGEMENT -------------- */
export const sendWelcomingMessage = Slack.sendWelcomingMessage;
/* -------- SCHEDULE CHANGES MANAGEMENT -------------- */
export const addScheduleChangeID = ScheduleChanges.addScheduleChangeID;
As seen in the code above, there are 16 functions that should be deployed to Firebase. However, only 12 get deployed. The following code snippet is from functions/src/groups/index.ts. In this file, the addGroupID is an existing function which continually gets deployed to Firebase. On the other hand, addGroupIDNewTestFunction is a new function that isn't getting deployed to Firebase even though they are in the same file and being referenced the same way.
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
export const addGroupID = functions.firestore
.document("organizations/{organizationID}/groups/{groupID}")
.onCreate(async (snap, context) => {
console.log("Adding group id");
await admin.firestore()
.doc(`organizations/${context.params.organizationID}/groups/${context.params.groupID}`).update({
'groupID': context.params.groupID
})
})
export const addGroupIDNewTestFunction = functions.firestore
.document("organizations/{organizationID}/groups2/{groupID}")
.onCreate(async (snap, context) => {
console.log("Adding group id");
await admin.firestore()
.doc(`organizations/${context.params.organizationID}/groups/${context.params.groupID}`).update({
'groupID': context.params.groupID
})
})
As mentioned previously, I have specified 16 functions in the main index.ts file that should get deployed to Firebase functions. However, only the existing 12 functions are getting deployed. The following code snippet is the output firebase gives me when I run firebase deploy --only functions inside the Angular project.
firebase deploy --only functions
=== Deploying to 'university-scheduling'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions
> tslint --project tsconfig.json
no-unused-variable is deprecated. Since TypeScript 2.9. Please use the built-in compiler checks instead.
Could not find implementations for the following rules specified in the configuration:
use-input-property-decorator
use-output-property-decorator
use-host-property-decorator
Try upgrading TSLint and/or ensuring that you have all necessary custom rules installed.
If TSLint was recently upgraded, you may have old rules configured which need to be cleaned up.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/email/index.ts:2:13 - 'admin' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:2:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:3:13 - 'moment' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/index.ts:4:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:2:13 - 'admin' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:6:7 - 'request' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/slack/index.ts:7:7 - 'options' is declared but its value is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:3:1 - All imports on this line are unused.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:43:11 - 'groups' is declared but itsvalue is never read.
WARNING: /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions/src/users/index.ts:65:11 - 'uid' is declared but its value is never read.
Running command: npm --prefix "$RESOURCE_DIR" run build
> functions# build /Users/brandon/Dropbox/Bearforce_Scheduling/bearforce-website/functions
> tsc
✔ 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...
i functions: packaged functions (106.24 KB) for uploading
✔ functions: functions folder uploaded successfully
⚠ appEngineLocation us-central1
i functions: updating Node.js 6 function createUser(us-central1)...
i functions: updating Node.js 6 function deleteUser(us-central1)...
i functions: updating Node.js 6 function addSessionID(us-central1)...
i functions: updating Node.js 6 function addRoleID(us-central1)...
i functions: updating Node.js 6 function removeAllShiftsAssociatedWithRole(us-central1)...
i functions: updating Node.js 6 function addShiftID(us-central1)...
i functions: updating Node.js 6 function hourly_job(us-central1)...
i functions: updating Node.js 6 function changeShiftStatsTest(us-central1)...
i functions: updating Node.js 6 function addGroupID(us-central1)...
i functions: updating Node.js 6 function addPermissionID(us-central1)...
i functions: updating Node.js 6 function sendWelcomingMessage(us-central1)...
i functions: updating Node.js 6 function addScheduleChangeID(us-central1)...
✔ scheduler: all necessary APIs are enabled
✔ functions[addPermissionID(us-central1)]: Successful update operation.
✔ functions[createUser(us-central1)]: Successful update operation.
✔ functions[addShiftID(us-central1)]: Successful update operation.
✔ functions[changeShiftStatsTest(us-central1)]: Successful update operation.
✔ functions[sendWelcomingMessage(us-central1)]: Successful update operation.
✔ functions[hourly_job(us-central1)]: Successful update operation.
✔ functions[addSessionID(us-central1)]: Successful update operation.
✔ functions[deleteUser(us-central1)]: Successful update operation.
✔ functions[addGroupID(us-central1)]: Successful update operation.
✔ functions[removeAllShiftsAssociatedWithRole(us-central1)]: Successful update operation.
✔ functions[addScheduleChangeID(us-central1)]: Successful update operation.
✔ functions[addRoleID(us-central1)]: Successful update operation.
✔ Deploy complete!
Please note that it can take up to 30 seconds for your updated functions to propagate.
You should check the directory which is compiled js files.
The default is functions/lib/.
If you import like ../../foo.ts anywhere at functions/src or functions/src/tests, etc then the compiled js file is functions/lib/{any}/foo.js.
The deploy target files are functions/lib/*.js only. So, functions/lib/{any}/foo.js is ignored.
You should change directory or files structure.
If the reason is test files then you should meke tsconfig.json for deploy and exclude them.
I wanted to give you guys an update on the solution to the problem I described above. In one of my index.ts files, I had the following require statement, var mailgun = require('mailgun-js'). Whenever I replaced this the require statement with import * as mailgun from 'mailgun-js', all the functions were deployed properly.
The most confusing part about this whole issue was that I only received success messages even when things weren't working properly. I do thank you guys for the speedy support and all of your suggestions!!
I had the exact same problem and the solution was Editing functions/src/index.ts instead of functions/lib/index.js
In my case it's index.ts because of I selected that option when initialized the project with "firebase init", your case depends on it, can be index.js too, but always on /src and not in /lib.
I think that the /lib folder if for the compiled file.
When deploying functions the compiler converts the src/.ts files into "lib/src/.js" files.
Somehow I had some files hanging around from previous deployments in the "lib/*js" space. Sure enough these files were getting deployed but the files containing the new function I had created were located in "lib/src/*js. No new changes were being passed up into cloud functions.
and so I went into package.json and changed
"main": "lib/index.js",
to read
"main": "lib/src/index.js",
And to cleanup I deleted all .js files from "lib/
I was back in business.

Why do the firebase cli give a TypeError

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.

Deploying cloud functions to firebase successful in the CLI but none appear in the dashboard

I've been following the codelabs tutorial here to deploy my first functions to firebase. I've made it to step 8 of the tutorial ("Welcome new users").
The deploy looks successful when I run firebase deploy --only functions from within the functions subdirectory:
Marks-MacBook-Air-3:functions mf$ firebase deploy --only functions
=== Deploying to 'friendlychat-21221'...
i deploying functions Running command: npm --prefix "$RESOURCE_DIR"
run lint
functions# lint /Users/mf/Desktop/friendlychat-web/cloud-functions-start/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...
✔ Deploy complete!
But looking at my firebase dashboard, it doesn't look like they deployed after all:
I'm not even sure where to begin troubleshooting, since the logs in the cloud functions tab is empty.
Has anyone encountered this before and/or have a good troubleshooting strategy?
Update 1:15 PM Friday 25 May, 2018: This is my index.js file in the functions subdirectory:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
// TODO(DEVELOPER): Write the addWelcomeMessages Function here.
// Adds a message that welcomes new users into the chat.
exports.addWelcomeMessages = functions.auth.user().onCreate(user => {
console.log('A new user signed in for the first time.');
const fullName = user.displayName || 'Anonymous';
// Saves the new welcome message into the database
// which then displays it in the FriendlyChat clients.
return admin.database().ref('messages').push({
name: 'Firebase Bot',
photoUrl: '/images/firebase-logo.png', // Firebase logo
text: `${fullName} signed in for the first time! Welcome!`, // Using back-ticks.
}).then(() => {
console.log('Welcome message written to database.');
});
});
// TODO(DEVELOPER): Write the blurOffensiveImages Function here.
// TODO(DEVELOPER): Write the sendNotifications Function here.
Here are the contents of the functions subdirectory:
I ended up getting it to work after changing two things (and I'm not sure which one fixed this issue; perhaps both):
run npm install from inside the functions directory before you deploy the functions (which should be done in the parent directory).
Be aware that when you run firebase init and cause an overwrite of your index.js file, that file may just have a commented out 'helloWorld' function...
Try Firebase list to list all the project that you have in firebase under the signed in account and see if the project you are deploying to shows up. In the case where it doesn't show try this:
firebase logout && firebase login
firebase list
firebase use <alias_or_project_id>
firebase deploy --only functions or firebase deploy --only functions:<function_name>
Hope this helps!

Resources