Search code examples
javascriptnode.jsfirebasegoogle-cloud-functionsfirebase-tools

Syntax Error when deploying Firebase cloud function V2


Here is the code


import {logger} from 'firebase-functions/v2';
import {getDatabase} from 'firebase-admin/database';
import {onSchedule} from "firebase-functions/v2/scheduler";

import {initializeApp} from "firebase-admin/app";


const app = initializeApp();
const database = getDatabase(app);

exports.scheduledfunction = onSchedule("* * * * *", async (event) => {
    // Fetch all user details.
    logger.log('test');
});

And here is the error:

Error: Functions codebase could not be analyzed successfully. It may have a syntax or runtime error

2 problems:

  1. I don't know where to look for more details about the error which make it very difficult to fix. Since it's a syntax error, I find nothing in the console logs. Maybe it's burried somewhere there.

  2. What is the syntax problem with this code?

And here is the functions json:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "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": "18"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^11.8.0",
    "firebase-functions": "^4.3.1"
  },
  "devDependencies": {
    "firebase-functions-test": "^3.1.0"
  },
  "private": true
}

Solution

  • It turns out that in order to use V2 functions with working code, I had to specifically use const/require syntax.

    Here is proof of concept working v2code:

    const {logger} = require('firebase-functions/v2');
    const {onSchedule} = require("firebase-functions/v2/scheduler");
    const {initializeApp} = require("firebase-admin/app");
    const {getDatabase} = require('firebase-admin/database');
    
    
    const app = initializeApp();
    const database = getDatabase(app);
    // Create and deploy your first functions
    // https://firebase.google.com/docs/functions/get-started
    
    // exports.helloWorld = onRequest((request, response) => {
    //   logger.info("Hello logs!", {structuredData: true});
    //   response.send("Hello from Firebase!");
    // });
    
    exports.minutecandidates = onSchedule({
            schedule: "* * * * *",
            minInstances: 1,
            maxInstances: 1,
            // include other options here from SchedulerOptions or GlobalOptions
        },
        async (context) => {
            logger.log("test");
        }
    );