Firebase functions cannot deploy : SyntaxError: Unexpected token function - node.js

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.

Related

Firebase Cloud Function - Parsing error: Unexpected token =>

I have a problem during deploy the functions into Cloud Function. I do believe before I put the const admin = require('firebase-admin') and admin.initializeApp() there will be a problem after I place these two, but before I place the two-line there is no problem occurred.
This is my full code for index.js
const functions = require("firebase-functions");
const express = require('express');
const cors = require('cors');
const admin = require('firebase-admin');
admin.initializeApp();
const app = express();
app.get('/', (req, res) => {
});
app.post("/", async (req, res) => {
const user = req.body;
await admin.firestore().collection("users").add(user);
res.status(201).send();
});
exports.user = functions.https.onRequest(app)
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": {
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0"
},
"devDependencies": {
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
.eslintrc.js
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};
Try adding the second part to your package.json:
{
"parserOptions": {
"ecmaVersion": 2017
}
}
"parser": "babel-eslint" - add this to your.eslintrc.js and run npm install babel-eslint --save this will resolve the issue.

Can't update firebase function to node 12 in Angular Universal app with AngularFire

I followed this tutorial to deploy Angular Universal to a firebase function and deploy with Firebase: https://medium.com/#chris.duebbert/angular-9-universal-firebase-deploy-8d8d47244e1c
Everything worked fine until I add AngularFireModule to my app.module.ts. Then when I run 'ng deploy' using node 12 I get the following error in the logs of my 'ssr' function:
Provided module can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: ReferenceError: globalThis is not defined
When I try with my local node version set to 10 I get the same error directly in my terminal.
Apparently, Firebase uses globalThis which requires node version 12 (Angular 11 run on SSR #nguniversal/express-engine ReferenceError: globalThis is not defined). I added the following to my /functions/package.json:
app.module.ts
"engines": {
"node": "12"
},
I can put any number for node version and my SSR function is still deploying with node 10 and the 'globalThis' error continues. I'm using Firebase's Blaze plan. Here's my app.module.ts:
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'serverApp' }),
AppRoutingModule,
NoopAnimationsModule,
FormsModule,
NgxTwitterTimelineModule,
AngularFireModule.initializeApp(config),
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
functions/package.json
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"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": "12"
},
"main": "lib/index.js",
"dependencies": {
"firebase-admin": "^9.4.2",
"firebase-functions": "^3.13.0",
"grpc": "^1.24.4"
},
"devDependencies": {
"tslint": "^5.12.0",
"typescript": "^3.8.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
You need to polyfill globalThis https://github.com/angular/angularfire#polyfills
Two weeks looking for a solution, until I have found this question/answer. Thank you!
Steps to solve the problem:
> npm install globalthis
on server.ts file:
import 'globalthis/auto';

Google cloud function with puppeteer does not work, even though it works in firebase functions emulator

So I made this function. It works correctly in firebase functions emulator, but when i use firebase deploy --only functions, I am getting errors like the ones on the picture. Any idea what I am doing wrong?
Here is my package.json
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions -P default",
"serve-dev": "npm run build && firebase serve --only functions -P staging",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions -P default",
"deploy-dev": "firebase deploy --only functions -P staging",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"#google-cloud/functions-framework": "^1.7.1",
"#types/node-fetch": "^2.3.3",
"firebase-admin": "^9.4.1",
"firebase-functions": "^3.11.0",
"golang": "^0.1.5-stable",
"node-fetch": "^2.5.0",
"puppeteer": "5.4.1",
"xml2js": "^0.4.19"
},
"devDependencies": {
"tslint": "^5.20.1",
"typescript": "^3.9.2"
},
"private": true,
"engines": {
"node": "10"
}
}
Here is the code of the function, it is in TypeScript, which after building becomes js ofc:
export const RecurringTradingUpdate = functions.https.onRequest(async (request, response) => {
const browser = await puppeteer.launch({
headless: true
});
const page = await browser.newPage();
await page.goto('website');
await page.waitFor(2000);
//await page.click('input[type=password]');
await page.click('#inputPassword');
await page.keyboard.sendCharacter('password')
//await page.click('button[type=submit]');
await page.click('#clickPassword');
await page.waitFor(2000);
//await page.click('button[type=submit]');
await page.click('#submit');
await page.waitFor(120000)
response.send("All done.")
});

google.docs is not a function

I want to use Google's Docs API but am running into an issue. I followed https://developers.google.com/docs/api/quickstart/nodejs but am having trouble setting it up.
My index.js looks like this:
const functions = require('firebase-functions');
const {google} = require('googleapis');
const {WebhookClient} = require('dialogflow-fulfillment');
const {SimpleResponse, BasicCard, SignIn, Image} = require('actions-on-google');
const calendar = google.calendar('v3');
const people = google.people('v1');
const drive = google.drive('v3');
const docs = google.docs('v1');
process.env.DEBUG = 'dialogflow:*'; // Enable lib debugging statements
My package.json:
"name": "DialogflowFirebaseWebhook",
"description": "Firebase Webhook dependencies for a Dialogflow agent.",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "6"
},
"scripts": {
"lint": "semistandard --fix \"**/*.js\"",
"start": "firebase deploy --only functions, node index.js",
"deploy": "firebase deploy --only functions"
},
"dependencies": {
"firebase-functions": "^2.0.2",
"firebase-admin": "^5.13.1",
"googleapis": "^27.0.0",
"actions-on-google": "2.2.0",
"dialogflow-fulfillment": "0.6.1",
"dialogflow": "0.6.0",
"client-oauth2": "4.2.5"
}
}
Showing only the relevant parts of my script, since it's pretty long, I get this error when I try to run the actual script.
Detailed stack trace: TypeError: google.docs is not a function
Any ideas what I am doing wrong?
Turning my comment into an answer...
It doesn't look like you have anywhere near the current version39 of google apis installed.
You have version 27.
Please run npm install googleapis#39 --save like the doc says.

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");

Resources