Firebase in Node: functions is not a function
When initializing Firebase as follows:
const firebase = require("firebase/app");
require("firebase/functions");
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const firebaseFunctions = firebaseApp.functions();
and after upgrading from version 8.10.1 to 10.5.2 the following error was reported:
TypeError: firebaseApp.functions is not a function
at Object.<anonymous> (/data/app.js:47:39)
at Module._compile (node:internal/modules/cjs/loader:1205:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1259:10)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
This is due a change in the Firebase SDK and a move from the namespaced style to the modular style as described in their Upgrade from the namespaced API to the modular API documentation.
There are two ways to resolve this issue. One is to use the namespaced (compat) library:
const firebase = require("firebase/compat/app");
require("firebase/compat/functions");
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const firebaseFunctions = firebaseApp.functions();
and the other is with the modular style:
const firebase = require("firebase/app");
const firebaseApp = firebase.initializeApp(firebaseConfig);
const firebaseFunctions = require("firebase/functions").getFunctions(firebaseApp);
Update: hat tip also to this Stack Overflow answer by Dharmaraj which contains an ES6 soliution.