Firebase Cloud Functions Deploy Error- SyntaxError: Unexpected token '?' - node.js

I just updated to:
npm: 8.11.0
node: v16.15.1
New Edit:
I just updated again sudo n latest:
npm: 8.12.1
node: v18.4.0
I'm trying to deploy a new cloud function firebase deploy --only functions:deleteUser
but I keep getting a cli error:
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
When I look at the log:
deleteUser
Detailed stack trace: /workspace/node_modules/firebase-admin/lib/app/firebase-namespace.js:84
this.INTERNAL = new FirebaseNamespaceInternals(appStore ?? new lifecycle_1.AppStore());
Provided module can't be loaded.
Is there a syntax error in your code?
SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/workspace/node_modules/firebase-admin/lib/default-namespace.js:19:30)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
Could not load the function, shutting down.
Index.js:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
exports.deleteUser = functions.https.onCall((data, context) => {
const userID = data.userID;
admin.auth().deleteUser(userID)
.then(() => {
console.log('Successfully deleted userID: ', userID);
return true // without this Return I get a different error: Each then() should return a value or throw promise/always-return
})
.catch((error) => {
console.log('Error deleting user: ', error);
});
});
New Edit Again
Package.json:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"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": "12"
},
"main": "index.js",
"dependencies": {
"#google-cloud/logging": "^8.1.1",
"firebase-admin": "^11.0.0",
"firebase-functions": "^3.11.0",
"save": "^2.4.0"
},
"devDependencies": {
"eslint": "^5.12.0",
"eslint-plugin-promise": "^4.0.1",
"firebase-functions-test": "^0.2.0"
},
"private": true
}

Thanks to the tip by #raina77ow in the comments. I had to go inside my package.json file and simply change the node version from 12 to 16
old:
"engines": {
"node": "12" // causes error
}
new:
"engines": {
"node": "16" // error is now gone
}

For users in node 12.x version:
npm install --save firebase-admin#10.3

The suggested solutions didn't work for me because I already use node version 16. What worked for me was replacing the firebase toolset with the latest version. I was surprised but it cleared the error. You can do that using the following command:
sudo npm install -g firebase-tools#latest --force
Now be aware that --force shouldn't be used unless you want to really replace the existing toolset (In general some should be careful with that command). Sudo was necessary in my case to execute the command with elevated rights. After that firebase deployment should work.

Related

Typesctipt error with Firestore functions: SyntaxError: Unexpected token 'export'

I am doing the Fireship Cloud Functions Course course. In that lesson he is covering HTTP cloud functions. I have literally line for line the same exact code but I get this error when I run firebase serve --only functions
+ functions: Using node#14 from host.
i functions: Watching "C:\Users\lover\CS-230\WVU_CS230_2021.08_Group06\COVID19-Tracker\functions" for Cloud Functions...
! C:\Users\lover\CS-230\WVU_CS230_2021.08_Group06\COVID19-Tracker\functions\src\index.ts:1
export { basicHTTP } from './http';
^^^^^^
SyntaxError: Unexpected token 'export'
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:93:18)
at initializeRuntime (C:\Users\lover\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:640:29)
at processTicksAndRejections (internal/process/task_queues.js:95:5)
at async handleMessage (C:\Users\lover\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:684:20)
! We were unable to load your functions code. (see above)
- It appears your code is written in Typescript, which must be compiled before emulation.
- You may be able to run "npm run build" in your functions directory to resolve this.
I tried npm build before running, I tried installing yarn as per this recommendation, and I have also tried npm run serve. None have which have helped.
I have node.js v14.18.0 installed, express.js v4.17.1, firebase v9.4.1, and I am using windows 10.
Below is the entirety of my https.ts file
import * as functions from 'firebase-functions'
import * as admin from 'firebase-admin'
admin.initializeApp(); // we only need to call this once in ONE file!
//if this is done more than once error for duplicate apps will appear
export const basicHTTP = functions.https.onRequest((request, response) => {
response.send('Hello from FireBase!');
});
Below is the entirety of my index.ts file
export { basicHTTP } from './http';
And finally my package.json file
{
"name": "functions",
"scripts": {
"lint": "eslint --ext .js,.ts .",
"build": "tsc",
"serve": "npm run build && firebase emulators:start --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "14"
},
"main": "./src/index.ts",
"dependencies": {
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1"
},
"devDependencies": {
"#typescript-eslint/eslint-plugin": "^3.9.1",
"#typescript-eslint/parser": "^3.8.0",
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-import": "^2.22.0",
"firebase-functions-test": "^0.2.0",
"typescript": "^3.8.0"
},
"private": true
}
How can I fix this?
You can't deploy ts code, you need to compile it to normal js. In this case you can just use npm run build and then try again.

How to use node-fetch with Cloud Functions for Firebase. Can't deploy

I wanna get data with Cloud Functions call from Flutter.
Here is my code.
const functions = require("firebase-functions");
const admin = require('firebase-admin');
const fetch = require('node-fetch');
admin.initializeApp();
exports.postalCode = functions.https.onCall( (data, context) => {
const URL = 'https://zipcloud.ibsnet.co.jp/api/search?zipcode=100-0002';
return fetch(URL).then(res => res.json());
});
Error code
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/xxx/node_modules/node-fetch/src/index.js
require() of ES modules is not supported.
require() of /Users/xxx/node_modules/node-fetch/src/index.js from /Users/xxx/xxx/functions/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename /Users/xxx/node_modules/node-fetch/src/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/xxx/node_modules/node-fetch/package.json.
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1102:13)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:92:18)
at Object.<anonymous> (/Users/nagayamasaru/Togashop/functions/index.js:3:15)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
package.json
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"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"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^9.8.0",
"firebase-functions": "^3.14.1",
"node-fetch": "file:node_modules/node-fetch"
},
"devDependencies": {
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
How to Solve??? Thanks your support from Japan
You should use node-fetch#2.6.1 because node-fetch only support ESM recent versions.
related: Instead change the require of index.js, to a dynamic import() which is available in all CommonJS modules

I get "AssertionError [ERR_ASSERTION]: Task function must be specified" when I run gulp

For some context, I'm trying to develop apps for Microsoft Teams. So I decided to follow the 'Hello World' project but I ran into an issue when generating the app package(a zip file). I'm on Win10
Here are my versions of node and gulp
$ gulp -v
CLI version: 2.2.0
Local version: 4.0.0
$ node -v
v12.14.1
My Error :(
$ gulp
assert.js:374
throw err;
^
AssertionError [ERR_ASSERTION]: Task function must be specified
at Gulp.set [as _setTask] (C:\Users\Comp\source\entitled\msteams-samples-hello-world-nodejs\node_modules\undertaker\lib\set-task.js:10:3)
at Gulp.task (C:\Users\Comp\source\entitled\msteams-samples-hello-world-nodejs\node_modules\undertaker\lib\task.js:13:8)
at Object.<anonymous> (C:\Users\Comp\source\entitled\msteams-samples-hello-world-nodejs\gulpfile.js:17:6)
at Module._compile (internal/modules/cjs/loader.js:955:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Module.require (internal/modules/cjs/loader.js:848:19)
at require (internal/modules/cjs/helpers.js:74:18)
at execute (C:\Users\Comp\AppData\Roaming\npm\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js:36:18) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
}
package.json
{
"name": "msteams-nodejs-hello-world",
"version": "1.0.0",
"description": "Microsoft Teams Node.js Hello World App. Start here to build your first app on the Teams platform.",
"scripts": {
"start": "node src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/OfficeDev/msteams-samples-hello-world-nodejs.git"
},
"author": "Microsoft Corp.",
"license": "MIT",
"bugs": {
"url": "https://github.com/OfficeDev/msteams-samples-hello-world-nodejs/issues"
},
"homepage": "https://learn.microsoft.com/en-us/microsoftteams/platform/get-started/get-started-nodejs",
"dependencies": {
"botbuilder": "^3.11.0",
"botbuilder-teams": "^0.1.6",
"config": "^1.28.1",
"express": "^4.16.2",
"faker": "^4.1.0",
"natives": "^1.1.6",
"node": "^10.13.0",
"pug": "^2.0.4"
},
"devDependencies": {
"del": "^3.0.0",
"gulp": "^4.0.0",
"gulp-install": "^1.1.0",
"gulp-zip": "^4.0.0"
}
}
gulpfile.js
var gulp = require('gulp');
var zip = require('gulp-zip');
var del = require('del');
gulp.task('clean', function() {
return del([
'manifest/**/*'
])
});
gulp.task('generate-manifest', function() {
gulp.src(['src/static/images/contoso*', 'src/manifest.json'])
.pipe(zip('helloworldapp.zip'))
.pipe(gulp.dest('manifest'));
});
gulp.task('default', ['clean', 'generate-manifest'], function() {
console.log('Build completed. Output in manifest folder');
});
I've read through some other articles with where I had to downgrade node and gulp but I've had no luck.
gulp.task('generate-manifest', function() {
return gulp.src(['src/static/images/contoso*', 'src/manifest.json']) // change here
.pipe(zip('helloworldapp.zip'))
.pipe(gulp.dest('manifest'));
});
gulp.task('default', gulp.series('clean', 'generate-manifest', function() { // change here
console.log('Build completed. Output in manifest folder');
}));
No need to downgrade gulp or node. You just need to use gulp4 syntax instead of gulp3.

firebase show error when i try to run functions locally

Showing the Firebase error whenever I run the function locally using emulator in CLI
$ firebase emulators:start --only functions
Starting emulators: ["functions"]
functions: Using node#8 from host.
functions: Emulator started at http://localhost:5001
functions: Watching "E:\dir\functions" for Cloud Functions...
Error: Cannot find module 'E:\dir\functions'
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 C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:459:29
at Generator.next ()
at C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:7:71
at new Promise ()
at __awaiter (C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:3:12)
at main (C:\Users\d\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:421:12)
Your function was killed because it raised an unhandled error.
I use typescript to write cloud functions.
here is my index.ts
import * as functions from 'firebase-functions';
import * as admin from "firebase-admin";
var cert = require("./skey.json");
admin.initializeApp({
credential: admin.credential.cert(cert),
databaseURL: "https://bhau-tk.firebaseio.com"
});
exports.basicHTTP = functions.https.onRequest((req, res) => {
res.send("Hello world!!");
})
package.json contains
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "8"
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "~7.0.0",
"firebase-functions": "^2.3.0",
"firebase-functions-test": "^0.1.6"
},
"devDependencies": {
"tslint": "^5.12.0",
"typescript": "^3.2.2"
},
"private": true
}
and project structure is
You should keep in mind that your project configuration is compiling TS sources files under src and putting the resulting JavaScript files in lib. So, you should refer to things in your functions folder relative to that location.
Since your compiled index.js is in lib, and your skey.json file is under src, you will have to refer to it that way:
var cert = require("../src/skey.json");
However, I wouldn't do it that way. I'd put skey.json in the functions folder (since it's not source code), and refer to it like this:
var cert = require("../skey.json");

Firebase functions cannot deploy : SyntaxError: Unexpected token function

I am trying to deploy a function to firebase and I get an error during deployment
Error: Functions did not deploy properly.
Could it be linked with the async function ?
Actual behavior
Functions get deployed with errors, the cli shows me the following message:
================ console log ================
> 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...
i functions: packaged functions (56.39 KB) for uploading
✔ functions: functions folder uploaded successfully
i functions: updating function sendContactEmailOAuth...
⚠ functions[sendContactEmailOAuth]: Deployment error.
Function load error: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /user_code/index.js:13
async function getJwt() {
^^^^^^^^
================ functions index.js file ================
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const { JWT } = require('google-auth-library/build/src/index');
exports.sendContactEmailOAuth = functions.https.onRequest((req, res) => {
const sender_msg = 'just a test'
const email = 'contact#lechorodescharentes.org'
async function getJwt() {
const client = new JWT(
functions.config().service_key.client_email,
null,
functions.config().service_key.private_key,
['https://www.googleapis.com/auth/cloud-platform', 'https://mail.google.com'],
);
await client.authorize();
const url = `https://www.googleapis.com/dns/v1/projects/${functions.config().service_key.project_id}`;
const res = await client.request({ url });
console.log(res.data);
}
getJwt();
/* send email with nodemailer to be inserted here */
});
================ package.json file ================
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase serve --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"dependencies": {
"firebase-admin": "~5.12.0",
"firebase-functions": "^1.0.2",
"firebase-tools": "^3.18.4",
"google-auth-library": "^1.4.0",
"nodemailer": "^4.6.4"
},
"devDependencies": {
"eslint": "^4.12.0",
"eslint-plugin-promise": "^3.6.0"
},
"private": true
}
As of September 2019:
Update firebase-admin : npm install --save firebase-admin
Update firebase-functions : npm install --save firebase-functions
Add "engines": { "node": "10" } to your /functions/package.json
...
"dependencies": {
"firebase-admin": "^8.5.0",
"firebase-functions": "^3.2.0"
},
"devDependencies": {
"tslint": "~5.19.0",
"typescript": "~3.6.2"
},
"engines": {
"node": "10"
}
...
As of August 2018:
Cloud Functions now support Node 8 (8.11.1). Check out this blog post.
Upgrade to Node 8
As suggested in this blog post, follow these steps to upgrade to Node 8:
Upgrade your firebase-functions version via npm install --save firebase-functions#latest
Upgrade firebase-tools via npm update -g firebase-tools
Add "engines": { "node": "8" } to your /functions/package.json
If you are still having the issue on a recent version (such as node 12), use the ecmaVersion parser option in your .eslintrc.js file.
Here's a sample:
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
parserOptions: {
ecmaVersion: 8,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};
h/t to Dean for the original suggestion.

Resources