Cannot find module 'firebase-admin/app' (only on deploy) - firebase

Environment
Firebase SDK version: 8.10.0
Firebase Product: admin
Node.js version: 16
NPM version: 8.1.0
Problem
Can't deploy Firebase Functions anymore. It all works perfectly on localhost, also deployed same firebase-admin before and out of nowhere got this error.
Steps to reproduce:
Tried to deploy Functions and can't deploy any of them all of a sudden.
Relevant Code:
const { initializeApp, cert } = require('firebase-admin/app')
package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"engines": {
"node": "16"
},
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"axios": "^0.27.2",
"busboy": "^1.6.0",
"cookie-parser": "^1.4.4",
"cors": "^2.8.5",
"dayjs": "^1.11.5",
"firebase-admin": "8.10.0",
"firebase-functions": "3.22.0",
"form-data": "^4.0.0",
"gotenberg-js-client": "^0.7.3",
"install": "0.13.0",
"morgan": "^1.10.0",
"nodemailer": "^6.4.6",
"npm": "8.19.2",
"pdf-lib": "^1.17.1",
"pdf.js-extract": "^0.1.4",
"pdfkit": "^0.13.0",
"webdav": "^3.2.0"
},
"private": true
}
i deploying functions
⚠ functions: package.json indicates an outdated version of firebase-functions.
Please upgrade using npm install --save firebase-functions#latest in your functions directory.
⚠ functions: Please note that there will be breaking changes when you upgrade.
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 (93.56 KB) for uploading
i functions: ensuring required API pubsub.googleapis.com is enabled...
i functions: ensuring required API cloudscheduler.googleapis.com is enabled...
✔ functions: required API cloudscheduler.googleapis.com is enabled
✔ functions: required API pubsub.googleapis.com is enabled
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 16 function api(europe-central2)...
i functions: updating Node.js 16 function sendExpiringCasesToHQ(us-central1)...
i functions: updating Node.js 16 function sendReportedCasesToHQ(us-central1)...
Functions deploy had errors with the following functions:
api(europe-central2)
sendExpiringCasesToHQ(us-central1)
sendReportedCasesToHQ(us-central1)
Because there were errors creating or updating functions, the following functions were not deleted
To delete these, use firebase functions:delete
i functions: cleaning up build files...
Error: There was an error deploying functions:
- Error Failed to update function api in region europe-central2
- Error Failed to update function sendExpiringCasesToHQ in region us-central1
- Error Failed to update function sendReportedCasesToHQ in region us-central1
2022-11-02T09:51:33.196805Z ? sendReportedCasesToHQ: Provided module can't be loaded.
2022-11-02T09:51:33.196846Z ? sendReportedCasesToHQ: Did you list all required modules in the package.json dependencies?
2022-11-02T09:51:33.196856Z ? sendReportedCasesToHQ: Detailed stack trace: Error: Cannot find module 'firebase-admin/app'
2022-11-02T09:51:33.196863Z ? sendReportedCasesToHQ: Require stack:
2022-11-02T09:51:33.196908Z ? sendReportedCasesToHQ: - /workspace/initFirebaseAdmin.js
2022-11-02T09:51:33.196915Z ? sendReportedCasesToHQ: - /workspace/index.js
2022-11-02T09:51:33.196923Z ? sendReportedCasesToHQ: - /layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/loader.js
2022-11-02T09:51:33.196931Z ? sendReportedCasesToHQ: - /layers/google.nodejs.functions-framework/functions-framework/node_modules/#google-cloud/functions-framework/build/src/main.js
2022-11-02T09:51:33.196941Z ? sendReportedCasesToHQ: at Function.Module._resolveFilename (node:internal/modules/cjs/loader:956:15)
2022-11-02T09:51:33.196950Z ? sendReportedCasesToHQ: at Function.Module._load (node:internal/modules/cjs/loader:804:27)
2022-11-02T09:51:33.196958Z ? sendReportedCasesToHQ: at Module.require (node:internal/modules/cjs/loader:1028:19)
2022-11-02T09:51:33.196966Z ? sendReportedCasesToHQ: at require (node:internal/modules/cjs/helpers:102:18)
2022-11-02T09:51:33.196979Z ? sendReportedCasesToHQ: at Object.<anonymous> (/workspace/initFirebaseAdmin.js:1:33)
2022-11-02T09:51:33.196986Z ? sendReportedCasesToHQ: at Module._compile (node:internal/modules/cjs/loader:1126:14)
2022-11-02T09:51:33.196994Z ? sendReportedCasesToHQ: at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
2022-11-02T09:51:33.197Z ? sendReportedCasesToHQ: at Module.load (node:internal/modules/cjs/loader:1004:32)
2022-11-02T09:51:33.197008Z ? sendReportedCasesToHQ: at Function.Module._load (node:internal/modules/cjs/loader:839:12)
2022-11-02T09:51:33.197015Z ? sendReportedCasesToHQ: at Module.require (node:internal/modules/cjs/loader:1028:19)
2022-11-02T09:51:33.197467Z ? sendReportedCasesToHQ: Could not load the function, shutting down.
2022-11-02T09:51:33.355972094Z E sendReportedCasesToHQ: Function cannot be initialized. Error: function terminated. Recommended action: inspect logs for termination reason. Additional troubleshooting documentation can be found at https://cloud.google.com/functions/docs/troubleshooting#logging

Related

Deploying firebase cloud functions in github actions with firebase-tools not working, but also no error

I am trying to run a github actions workflow on each push to the main branch. The workflow is supposed to deploy firebase cloud functions (in the /functions dir).
The whole workflow gets triggered by the push correctly and runs without errors, but the functions do not get deployed.
deploy-cloud-functions-merge.yml
name: Deploy Cloud Functions
on:
workflow_dispatch:
push:
branches:
- main
paths:
- 'functions/**'
jobs:
build_and_deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout#v3
- uses: actions/setup-node#v3
with:
node-version: 16.x
- name: Build Cloud Functions
run: cd functions && npm ci
- name: Create SA key
run: echo '${{ secrets.CLOUD_FUNCTIONS_SERVICE_ACCOUNT }}' > $HOME/gcloud.json
- name: Deploy Cloud Functions
run: export GOOGLE_APPLICATION_CREDENTIALS=$HOME/gcloud.json && cd functions && npx firebase-tools deploy --only functions --project default --json && npx firebase-tools --version
The output in github actions from the Deploy Cloud Functions step:
Run export GOOGLE_APPLICATION_CREDENTIALS=$HOME/gcloud.json && cd functions && npx firebase-tools deploy --only functions --project default --json && npx firebase-tools --version
npm WARN exec The following package was not found and will be installed: firebase-tools#11.23.0
npm WARN deprecated uuid#3.4.0: Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.
npm WARN deprecated request#2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated har-validator#5.1.3: this library is no longer supported
npm WARN deprecated debug#4.1.1: Debug versions >=3.2.0 <3.2.7 || >=4 <4.3.1 have a low-severity ReDos regression when used in a Node.js environment. It is recommended you upgrade to 3.2.7 or 4.3.1. (https://github.com/visionmedia/debug/issues/797)
> lint
> eslint
11.23.0
So after the predeploy script (lint + eslint), there is no output, but also no error.
When I run firebase deploy --only functions --project default on the same project locally, this is what the output looks like:
=== Deploying to '[projectname]'...
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> lint
> eslint
✔ 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...
i artifactregistry: ensuring required API artifactregistry.googleapis.com is enabled...
✔ artifactregistry: required API artifactregistry.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
✔ functions: required API cloudfunctions.googleapis.com is enabled
i functions: preparing codebase default for deployment
⚠ functions: package.json indicates an outdated version of firebase-functions. Please upgrade using npm install --save firebase-functions#latest in your functions directory.
i functions: preparing functions directory for uploading...
i functions: packaged /home/stanley/[projectname]/functions (82.34 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating Node.js 16 function getFileParts(europe-west1)...
i functions: updating Node.js 16 function getCustomMeta(europe-west1)...
i functions: updating Node.js 16 function getCSVParts(europe-west1)...
i functions: updating Node.js 16 function getTemplates(europe-west1)...
i functions: updating Node.js 16 function getCSVLink(europe-west1)...
✔ functions[getCustomMeta(europe-west1)] Successful update operation.
✔ functions[getTemplates(europe-west1)] Successful update operation.
✔ functions[getCSVParts(europe-west1)] Successful update operation.
✔ functions[getCSVLink(europe-west1)] Successful update operation.
✔ functions[getFileParts(europe-west1)] Successful update operation.
Function URL [functionurl]
Function URL [functionurl]
Function URL [functionurl]
Function URL [functionurl]
Function URL [functionurl]
i functions: cleaning up build files...
✔ Deploy complete!
Project Console: [console-link]
I am using --project default, to fix a previous error:
***
"status": "error",
"error": "No project active, but project aliases are available.\n\nRun \u001b[1mfirebase use <alias>\u001b[22m with one of these options:\n\n default ([projectname])\n staging ([projectname])"
***
this is what my .firebaserc looks like:
{
"projects": {
"default": "[projectname]",
"staging": "[projectname]"
},
"targets": {
"[projectname]": {
"hosting": {
"[projectname]": [
"[otherprojectname]"
]
}
}
},
"etags": {}
}
I am basically out of solutions and would appreciate any suggestions.

firebase functions deploy error : ERR_PACKAGE_PATH_NOT_EXPORTED

I was following the in-app-purchase part in Google Codelab, But after I finish all steps and finally run firebase deploy this error has appeared.
I have read many solutions about the simillar problems, for example, remove node-modules and package-lock file then re-install them, down grade node version to 14, downgrade firebase-admin, firebase-functions...
But none of them works for me.
I'm totally desperate now. Please somebody help me. I already googled almost 72hours and I found nothing.
And here is the contents of terminal show up after I run firebase deploy.
% firebase deploy
=== Deploying to 'server-259035'...
i deploying firestore, functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint /Users/functions
> eslint --ext .js,.ts .
Running command: npm --prefix "$RESOURCE_DIR" run build
> functions# build /Users/functions
> tsc
✔ functions: Finished running predeploy script.
i firestore: reading indexes from firestore.indexes.json...
i cloud.firestore: checking firestore.rules for compilation errors...
✔ cloud.firestore: rules file firestore.rules compiled successfully
i functions: ensuring required API cloudfunctions.googleapis.com is enabled...
i functions: ensuring required API cloudbuild.googleapis.com is enabled...
✔ functions: required API cloudfunctions.googleapis.com is enabled
✔ functions: required API cloudbuild.googleapis.com is enabled
i functions: preparing codebase default for deployment
Error: Failed to load function definition from source: Failed to generate manifest from function source: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/firestore' is not defined by "exports" in /Users/functions/node_modules/firebase-admin/package.json
And package.json file.
{
"name": "functions",
"scripts": {
"lint": "eslint --ext .js,.ts .",
"build": "tsc",
"watch": "tsc --watch",
"serve": "firebase emulators:start",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "lib/index.js",
"dependencies": {
"camelcase-keys": "^8.0.0",
"firebase-admin": "^11.0.1",
"firebase-functions": "^3.22.0",
"google-auth-library": "^8.0.2",
"googleapis": "^105.0.0",
"jest": "^28.1.3",
"lodash": "^4.17.21",
"node-apple-receipt-verify": "^1.12.1"
},
"devDependencies": {
"#types/node-apple-receipt-verify": "^1.7.1",
"#typescript-eslint/eslint-plugin": "^5.27.0",
"#typescript-eslint/parser": "^5.27.0",
"eslint": "^8.16.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-import": "^2.26.0",
"firebase-functions-test": "^2.3.0",
"typescript": "^4.7.2"
},
"private": true
}
I had the same issue when updated my package.json packages. I had to make the following change in order to fix it:
Before:
import firestore from "firebase-admin/lib/firestore";
After:
import firebaseAdmin from "firebase-admin";
** Add the prefix firebaseAdmin. to all the firestore references, eg: firebaseAdmin.firestore.Timestamp;*
I changed the following files:
app-store.purchase-handler.ts
google-play.purchase-handler.ts
iap.repository.ts
It happens with in_app_purchases flutter firebase example due to updated package names and their content. Full error is: Error: Failed to load function definition from source: Failed to generate manifest from function source: Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: Package subpath './lib/firestore' is not defined by "exports" in functions/node_modules/firebase-admin/package.json
You need to replace: import firestore from "firebase-admin/lib/firestore"; with import firebaseAdmin from "firebase-admin";
Now you need to go your .ts files and replace the same import above with the new one and correct the references for example: firestore.Timestamp now will be firebaseAdmin.firestore.Timestamp
All the files you need to make changes are these ones:
app-store.purchase-handler.ts
google-play.purchase-handler.ts
iap.repository.ts
I’ve fixed, upgraded and updated codelab example backend functions for verifying in app purcashe on backend. You can find updated code here, it works as expected for me with node 18.
https://github.com/vbalagovic/iap-firebase-backend

Nuxt SSR - Firebase Hosting

Going through the gauntlet of deploying a Nuxt SSR app to firebase hosting. I've been following this fantastic tutorial. Due to Firebase's limitations with es6-es7, I'm converting my "imports" to "require" and "module.exports". For some reason, when I run firebase deploy --only functions, the deploy fails with the following error:
import colors from 'vuetify/es5/util/colors'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/Users/bendepew/Developer/aw/pit-road-reporter/prr-nuxtjs/functions/index.js:12:20)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
When I check the error locations, I see that the code that I had manually changed to ES5 syntax has been auto-reverted to ES7 syntax. My first thought was that this could be an eslint issue, but I'm note sure.
PACKAGE.JSON Scripts
"scripts": {
"lint": "eslint",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
.ESLINT.JS
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};
Has anyone else experienced this issue while trying to deploy Nuxt SSR to Firebase Hosting via a Cloud Function?

Firebase deploy issue: Build failed: npm ERR! Maximum call stack size exceeded

I am trying to deploy my Firebase Cloud Function with:
firebase deploy --only functions:helloWorld
My problem is that the command is sometimes successful, but most times it is failing with the error above. What might be the cause, and how to fix it?
I came across a similar question and tried many of the recommended solutions (clearing the npm cache and reinstalling the dependencies). Both solutions do not work reliably for me.
Here is the full console output:
=== Deploying to '<my-firebase-project>'...
i deploying functions
✔ 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 (84.76 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: current functions in project: myFunction1(us-central1), myFunction2(us-central1), myFunction3(us-central1)...
i functions: uploading functions in project: helloWorld(us-central1)
i functions: updating Node.js 10 function helloWorld(us-central1)...
⚠ functions[helloWorld(us-central1)]: Deployment error.
Build failed: npm ERR! Maximum call stack size exceeded
npm ERR! A complete log of this run can be found in:
npm ERR! /builder/home/.npm/_logs/2020-10-15T17_38_33_530Z-debug.log; Error ID: 49341d49
Functions deploy had errors with the following functions:
helloWorld
To try redeploying those functions, run:
firebase deploy --only "functions:helloWorld"
To continue deploying other features (such as database), run:
firebase deploy --except functions
Error: Functions did not deploy properly.
Part of the problem is that I don't know where to find the full logs that the firebase deploy command output says are in /builder/home/.npm/_logs/2020-10-15T17_38_33_530Z-debug.log
And here are my firebase/functions config files:
./functions/index.js:
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!");
});
./firebase.json:
{
"functions": {
"predeploy": [
],
"source": "functions",
"runtime": "nodejs10"
},
"emulators": {
"functions": {
"port": 5001
},...
}
...
}
./functions/package.json:
{
"name": "functions",
"description": "Backend - Firebase Cloud Functions",
"version": "1.0.0",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14.3.0"
},
"dependencies": {
"config": "^3.3.1",
"core-util-is": "^1.0.2",
"crypto-js": "^4.0.0",
"firebase-admin": "^9.1.1",
"firebase-functions": "^3.11.0",
"myapp_config": "file:./config"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
Dev stack:
macOS 10.15+
node version = v14.3.0
Turns out the issue was how I was building the local dependency myapp_config in the line
"myapp_config": "file:./config". I re-architected my app to remove [the need for] this line altogether and so far have not seen the deployment error again.
The ./config indicated on that line was actually a symlink to the config folder on my project root that I created with: ln -s ./config ./functions/config originally intended to deliver project-wide configuration-related modules into my functions scripts without having to manually copy over those files into functions. I suppose that much as Firebase Functions supports local Node.js dependencies, the CLI/npm somehow gets confused by or doesn't work well with symlinks (my guess is that it sees ./config and its symlink ./functions/config and goes into some infinite loop between them)
This other question sheds more light on the code structure I had and the problem I was trying to solve in the first place.

Firebase deploy error - Cannot find module 'firebase'

I'm trying to deploy Google Cloud function triggers that trigger from db events, but when I run firebase deploy The functions aren't deployed properly and I get an error saying Error: Cannot find module firebase
When I was first creating the project I could deploy functions without any issues. It's been a few days since I last deployed anything, but now I'm getting this issue on all my functions (not just my trigger functions)
My function:
exports.deleteNotificationOnUnlike = functions
.region("us-central1")
.firestore.document("likes/{id}")
.onDelete((snapshot) => {
return db
.doc(`/notifications/${snapshot.id}`)
.delete()
.catch((err) => console.error(err));
});
Package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"dependencies": {
"busboy": "^0.3.1",
"firebase-admin": "^8.0.0",
"firebase-functions": "^3.1.0"
},
"devDependencies": {
"firebase-functions-test": "^0.1.6"
},
"private": true
}
Expecting the functions to deploy successfully but getting this error:
Error messages from firebase:
Code in file index.js can't be loaded.
Did you list all required modules in the package.json dependencies?
Detailed stack trace: Error: Cannot find module 'firebase'
at Function.Module._resolveFilename (module.js:548:15)
at Function.Module._load (module.js:475:25)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/handlers/users.js:5:18)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
{"#type":"type.googleapis.com/google.cloud.audit.AuditLog","status":{"code":3,"message":"INVALID_ARGUMENT"},"authenticationInfo":{"principalEmail":"*********"},"requestMetadata":{"requestAttributes":{},"destinationAttributes":{}},"serviceName":"cloudfunctions.googleapis.com","methodName":"google.cloud.functions.v1.CloudFunctionsService.CreateFunction","resourceName":"projects/*******/locations/us-central1/functions/createNotificationOnComment"}
I've seen some posts where people were missing some modules and needed to run an npm i XXX inside the functions folder, but I haven't seen any instances where it was saying that the firebase module couldn't be found, and I'm not sure what changes from my last successful deployment, or what module I might be missing.
Figured out the solution. I hadn't installed the firebase module in the functions folder but had included it in the parent folder of functions. I went into functions and ran npm install --save firebase and the deploy was successful.
Make sure you installed the package from the functions directory, Not the project directory. I got this error many times when I accidentally installed packages while in the project directory, It worked fine locally, but created such errors during deployment. So, goto functions and install from there
cd functions
npm install [your package]
Then it usually works fine
Try updating firebase npm package, mine was solved using npm install -D firebase.
-Stay Safe!

Resources