How to deploy express app on firebase hosting - firebase

I have built an express app and the folder structure is below.
Then i created firebase init hosting on a dummy folder and copied the firebase.json and .firebase files
I created index.js file
const functions = require('firebase-functions')
const app = require('./app');
exports.widgets = functions.https.onRequest(app);
firebase.json
{
"hosting": {
"public": "public",
"rewrite":[{
"source": "**",
"function": "widgets"
}],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
Also copied the index.html generated by firebase to public folder
On deployment i am getting index.html
If i delete index.html and run as localhost i am getting below output
How can i get the express app executed (as shown in localhost) instead of index.html on firebase deploy.
Edit 1
I am following link.
When i run firebase serve, i am getting this error
AssertionError [ERR_ASSERTION]: missing path at Module.require (module.js:583:3) at require (internal/module.js:11:18) at InitializeFirebaseAdminStubs (C:\Users\alaksandarjesus\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:231:18) at C:\Users\alaksandarjesus\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:451:9 at Generator.next () at C:\Users\alaksandarjesus\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:7:71 at new Promise () at __awaiter (C:\Users\alaksandarjesus\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:3:12) at main (C:\Users\alaksandarjesus\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:421:12) at Object. (C:\Users\alaksandarjesus\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:511:5)
When i tried to run firebase deploy
E:\ogst-server-firebase\functions>firebase deploy
=== Deploying to 'ogst-server-95fcc'...
i deploying functions, hosting
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
Error: An unexpected error has occurred.
The reason for this is missing public folder, and i created manually (which was expected to be created with firebase init functions).
E:\ogst-server-firebase\functions>firebase deploy
=== Deploying to 'ogst-server-95fcc'...
i deploying functions, hosting
i functions: ensuring necessary APIs are enabled...
+ functions: all necessary APIs are enabled
i functions: preparing functions directory for uploading...
i hosting[ogst-server-95fcc]: beginning deploy...
i hosting[ogst-server-95fcc]: found 0 files in public
+ hosting[ogst-server-95fcc]: file upload complete
i hosting[ogst-server-95fcc]: finalizing version...
+ hosting[ogst-server-95fcc]: version finalized
i hosting[ogst-server-95fcc]: releasing new version...
+ hosting[ogst-server-95fcc]: release complete
+ 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/ogst-server-95fcc/overview
Hosting URL: https://ogst-server-95fcc.firebaseapp.com
Now my deployment is successful. But i am getting 404
Answer
In the index.js file (following the above link), i did not change
module.exports = functions.https.onRequest(app); //wrong
to
exports.app = functions.https.onRequest(app); //correct
Thanks to all for the support

Firebase Hosting prefers to serve static content over rewrites that get sent to Cloud Functions. In other words, if a request could be served by any static content, that content will always take precedence over a rewrite to Cloud Functions.
If you want your web site root page to be served by Cloud Functions, this means you should not have an index.html in your public folder, since Firebase Hosting is finding that first.

Related

Firebase functions: RangeError [ERR_FS_FILE_TOO_LARGE]: File ... is greater than 2 GB

Been deploying a ton w/ no problems. Made a small change and now it bonks on deploy.
I rolled back a few commits and still get same error. Tried deploying only 1 function, same issue. Deleted a bunch of log files, etc. Same.
Quotas all look fine.
There's about 20 functions in the project.
i functions: Loaded environment variables from .env.
i functions: preparing functions directory for uploading...
[2023-01-17T07:51:09.242Z] RangeError [ERR_FS_FILE_TOO_LARGE]: File size (5067767843) is greater than 2 GB
at new NodeError (node:internal/errors:372:5)
at readFileHandle (node:internal/fs/promises:377:11)
at async getSourceHash (/Users/adrian/.nvm/versions/node/v16.16.0/lib/node_modules/firebase-tools/lib/deploy/functions/cache/hash.js:12:18)
at async packageSource (/Users/adrian/.nvm/versions/node/v16.16.0/lib/node_modules/firebase-tools/lib/deploy/functions/prepareFunctionsUpload.js:61:30)
at async prepare (/Users/adrian/.nvm/versions/node/v16.16.0/lib/node_modules/firebase-tools/lib/deploy/functions/prepare.js:131:36)
at async chain (/Users/adrian/.nvm/versions/node/v16.16.0/lib/node_modules/firebase-tools/lib/deploy/index.js:35:9)
at async deploy (/Users/adrian/.nvm/versions/node/v16.16.0/lib/node_modules/firebase-tools/lib/deploy/index.js:79:5)
Error: Could not read source directory. Remove links and shortcuts and try again.
What file is it referring to?
Appreciate any ideas.
A new type of log file had been generated which didn't match the current ignore pattern in firebase.json. So the log file was being processed during deploy.
Solution: update ignore pattern to cover any .log files
firebase.json
...
"functions": [
{
"source": "functions",
"codebase": "default",
"ignore": ["node_modules", ".git", "*.log"]
}
]
...

Firebase Functions Deployment Failure

I am not able to deploy my app into production. I only have firebase hosting and functions. On firebase serve everything works well.
I obtain the following error:
i deploying functions, hosting
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 (46.72 KB) for uploading
+ functions: functions folder uploaded successfully
i hosting[library-app-d49fe]: beginning deploy...
i hosting[library-app-d49fe]: found 19 files in public
+ hosting[library-app-d49fe]: file upload complete
i functions: updating Node.js 10 function app(us-central1)...
! functions[app(us-central1)]: Deployment error.
Function failed on loading 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
Functions deploy had errors with the following functions:
app
To try redeploying those functions, run:
firebase deploy --only "functions:app"
To continue deploying other features (such as database), run:
firebase deploy --except functions
My firebase.json looks like this
{
"hosting": {
"public": "public",
"rewrites": [{
"source": "**",
"function": "app"
}],
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
and my app.js in functions folder has the following export:
exports.app = functions.https.onRequest(app);
I am sorry if I don't provide the necessary details but I am clueless of what the issue might be.

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!

Firebase cannot understand what targets to deploy

When deploying the following hello-world equivalent code I get the error shown in the end:-
$ ls -lR
.:
total 8
-rw-r--r-- 1 hgarg hgarg 3 Aug 29 14:55 firebase.json
drwxr-xr-x 2 hgarg hgarg 4096 Aug 29 11:56 functions
./functions:
total 4
-rw-r--r-- 1 hgarg hgarg 1678 Aug 29 11:56 index.js
firebase.json looks like this:-
{}
and index.json like this:-
'use strict';
const functions = require('firebase-functions');
exports.search = functions.https.onRequest((req, res) => {
if (req.method === 'PUT') {
res.status(403).send('Forbidden!');
}
var category = 'Category';
console.log('Sending category', category);
res.status(200).send(category);
});
But deploying fails:-
$ firebase deploy
Error: Cannot understand what targets to deploy. Check that you specified valid targets if you used the --only or --except flag. Otherwise, check your firebase.json to ensure that your project is initialized for the desired features.
$ firebase deploy --only functions
Error: Cannot understand what targets to deploy. Check that you specified valid targets if you used the --only or --except flag. Otherwise, check your firebase.json to ensure that your project is initialized for the desired features.
it would be better to pre-populate the firebase with the default options. I choose that I wanted to use only hosting the firebase.json should have be created with the default hosting option.
{
"hosting": {
"public": "public"
}
}
or you try run firebase init again.
Faced similar issue. In firebase.json file (in hosting parameter), we have to give the name of directory that we want to deploy (in my case, I was already in the directory, which I wanted to deploy, hence I put "." in hosting specification). It solved the error for me.
{
"hosting": {
"public": ".",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
I was facing this issue when running:
firebase emulators:exec --only firestore 'npm tst'
The problem was that on firebase.json must have a property for the emulator you want. So in my case I added a "firestore": {} on firebase.json and worked.
I faced this problem too because at the beginning of my Firebase project setup, I only initialized the hosting feature. Later on, when I wanted to deploy firestore security rules with the Firebase CLI, my initialization process was not complete for this command to work as expected.
I could not run firebase deploy --only firestore:rules
because my firebase.json file was not initialized with defaults.
Easiest and most adequate way to fix this problem is to run the firebase init command again to setup all features you want to use. You could do it manually but you could miss details that the command line interface can setup for you in the exact way it needs to be for defaults.
Solution:
Run the firebase init command again
...and make sure to initialize every feature you are currently using. Take care not to overwrite important configs if you already have some by carefully reading the Firebase CLI instructions that are asked by the init command.
Firebase reads package.json to read details of the functions target. This file was missing from my project directory, as I had moved files around after doing an init.
Creating a clean directory and doing a firebase init functions inside it created all the required files and folders to get started.
I think you are missing on one of the following things -
a) you should run firebase init outside of the main project where index.html is.
b) select hosting option after running firebase init by pressing SPACE
c) Please give folder name which contain index.html in it.
And your project will be up running.

Firebase Serve Error

I am new to firebase and am trying to make a simple app that utilizes user authentication. At this point in the project I am trying to run firebase on a local server using CLI commands.
I have set up firebase init and firebase deploy. When I type firebase serve on my project folder i get the response,
"an unexpected error has occurred".
Below i am attaching the contents of my firebase-debug.log file. Any help would be appreciated. Thanks
command requires scopes:
["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase",...
[debug] [2017-06-11T17:09:09.607Z] > authorizing via signed-in user
TypeError: Cannot read property 'public' of undefined
Look in your firebase.json file, which you should have in the directory where you're running firebase serve. It should look something like this:
{
"hosting": {
"public": "app",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
If it doesn't have that "hosting" key, then you'll get that Cannot read property 'public' of undefined error because firebase serve tries to access .hosting.public.
I faced this issue today, I ran it with --debug and found out that I've installed npm/node as sudo user, running following:
firebase serve
was giving me this error:
Error: An unexpected error has occurred.
When I ran it with sudo, I was able to deploy hosting and functions locally:
sudo firebase serve --debug --only hosting,functions
1) create a folder called "public" and put your files inside.
2) edit the firebase.json and just write this:
{
"hosting": {
"public": "public"
}
}
This appears to be a bug - that ideally should be resolved with Firebase Init. I have logged a support ticket with Firebase, and would encourage others to do so as well.
I think you may have skipped an initialization step by accident (I did the same thing on my first run-through)
Try this (from your same project directory):
1) firebase init
2) When prompted for which services you'll need make sure that Database AND Hosting options have their markers highlighted green (tab to Hosting with the spacebar). It's easy to select just database and let it run its configuration and assume it configures all of the bulleted options below it if you do not watch closely because the stdout info isn't very clear. Now hit Enter
3) Accept the default database settings as you probably did before, and when asked "What do you want to use as your public directory? (public)", hit Enter.
At this point you should be good to go spin up a local firebase web server...
4) try 'firebase serve', hit Enter, and you should get a verification that hosting files are being served from /public
Hope this helps. Good luck.
As for me the error is (--debug attr)
Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/firebase-tools/node_modules/#google-cloud/functions-emulator/logs'
So the solution will be to run with sudo

Resources