javascriptnode.jsfirebasefirebase-realtime-databasegoogle-cloud-functions

Firebase functions V2: ; SyntaxError: Cannot use import statement outside a module at wrapSafe


I am trying to send notification to device when I receive message in chat in my app. At the moment I just want to read snapshot contents, but when trying to deploy, I am hit with an error: Firebase functions V2: ; SyntaxError: Cannot use import statement outside a module at wrapSafe

enter image description here


{
  "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": "20"
  },
  "dependencies": {
    "firebase-admin": "^10.0.2",
    "firebase-functions": "^3.18.0",
    "react-native-notifications": "^5.1.0"
  },
  "private": true
}

I am using Node.js v20 in functions 1st gen. Do you know how to fix this problem?

Thanks!

import { initializeApp } from "firebase-admin/app";
import { getAuth } from "firebase-admin/auth";
import { getDatabase } from "firebase-admin/database";
import { getMessaging } from "firebase-admin/messaging";
import { log, warn } from "firebase-functions/logger";
import { onValueWritten } from "firebase-functions/v2/database";

initializeApp();
const auth = getAuth();
const db = getDatabase();
const messaging = getMessaging();

export const sendPushNotification = onValueWritten("/Chat/{id}", async (event) => {
    const snapshot = event.data.after.val();

    log("SNAP IS");
    log(snapshot);
});

I now get this error with the same code
Function failed on loading user code. This is likely due to a bug in the user code. Error message: Provided module can't be loaded. Is there a syntax error in your code? Detailed stack trace: /workspace/index.js:1 import { initializeApp } from "firebase-admin/app"; ^^^^^^ SyntaxError: Cannot use import statement outside a module at wrapSafe (node:internal/modules/cjs/loader:1378:20) at Module._compile (node:internal/modules/cjs/loader:1428:41) at Module._extensions..js

Solution

  • I have been able to solve the problem by updating the function to V2:

    npm install firebase-admin@latest firebase-functions@latest
    

    I then deployed the following using

    firebase deploy --only functions
    

    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": "20"
      },
      "dependencies": {
        "firebase-admin": "^13.3.0",
        "firebase-functions": "^6.3.2",
        "react-native-notifications": "^5.1.0"
      },
      "private": true
    }
    
    

    index.js

    const { initializeApp } = require("firebase-admin/app");
    const { getDatabase } = require("firebase-admin/database");
    const { getMessaging } = require("firebase-admin/messaging");
    const { onRequest } = require("firebase-functions/v2/https");
    const { onValueWritten } = require("firebase-functions/v2/database");
    
    initializeApp();
    
    
    
    
    exports.newChildAddedWritten = onValueWritten("/Chat/{id}", async (event) => {
        const snapshot = event.data.after.val();
    
        let sender = snapshot.sname; // ...
        let body = snapshot.body;
        let from = snapshot.from;
    
        const payload = {
            notification: {
                title: sender,
                body: body
            },
            
    
            data: {
                custom_from: from // cannot use from here as it is reserved
             }
    }
    
    
     const tokenSnapshot = await getDatabase().ref(`/Users/${snapshot.to}`).once("value");
        const usersData = tokenSnapshot.val();
    
    
    
        let tokens = usersData.tokens;
        
        let filteredTokens = Object.keys(tokens).filter(key => key.length > 10);
    
    
        const message = {
            tokens: filteredTokens,
            notification: payload["notification"],
            data: payload["data"]
          };
    
    
          
      
          const response = await getMessaging().sendEachForMulticast(message);
          console.log(`Successfully sent messages: ${response.successCount}`);
          if (response.failureCount > 0) {
    
            response.responses.forEach((resp, idx) => {
                if (!resp.success) {
                  console.log("CURR-TOKEN: " + tokens[idx]);
                  console.error(`Error code: ${resp.error.code}`);
                  console.error(`Error message: ${resp.error.message}`);
                }
              });
    
    
            console.log(`Failed to send messages: ${response.failureCount}`);
          }
    
    });