What is the difference between Firebase SDK and Firebase SDK for cloud functions? - node.js

I don't understand the difference between Firebase SDK and Firebase SDK for cloud functions. I mean, when you run in command line "firebase init" in node.js, node modules will be downloaded to initialize a new project. But if i run "npm install firebase" different node modules appears, with similar names and different contents. So the question is: which SDK should I use to run functions and authentication in the same code? (I got a lot of require error from importing similar things and I don't know how to solve the problem).
Here is the code:
const functions = require('firebase-functions');
var firebase = require('firebase');
firebase.initializeApp();
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
exports.delete = functions.https.onRequest((request, response) => {
console.log("delete");
});
The error says firebase.auth() is not a function, maybe for bad import and I don't know which package I need to import

npm install firebase installs modules to be used in client code that accesses Firebase products such as Firebase Authentication, Realtime Database, Firestore, and Cloud Storage.
npm install firebase-functions install modules to be used when writing backend code to deploy to Cloud Functions.
You're trying to use the Firebase Authentication client side library to listen to auth state changes in Cloud Functions. This isn't going to work, since that auth library only works on web clients.

Related

How to fix TypeError when using signInWithCredential on node.js? [EDIT: bug in Firebase 6.2.2]

I am trying to sign in to firebase using a Google Id Token, as I'm developing an app that will be running on a raspberry pi, but when trying to sign in using the received token firebase crashes when using signInWithCredential. Here's my minimal reproducible example
var firebase = require("firebase/app");
require("firebase/auth");
const firebaseConfig = {
...
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const id_token = "A_GOOGLE_ID_TOKEN";
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
firebase.auth().signInWithCredential(credential);
and it crashes with
TypeError: this.f is not a constructor
at ai.a (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:188:361)
at yh (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:171:191)
at bi.o (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:193:175)
at ji (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:191:239)
at C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:197:181
at new C (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:18:736)
at pi (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:197:161)
at C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:209:203
at e.g (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:22:101)
at Kb (C:\Dev\Crashing\node_modules\#firebase\auth\dist\auth.js:25:195)
I tried it with several valid ID Tokens, but it seems that part is actually not broken, the credential itself appears to be fine, because signInWithCredential dies the same way even when I pass an arbitrary string as the id_token.
What am I doing wrong? Or could it possibly be an issue with Firebase JS SDK itself?
I am working on Windows 10, ver. 1809, running Node v10.15.3 and firebase JS SDK 6.2.2 (npm firebase package).
EDIT: I tried Firebase JS SDK version 6.2.0 and the code worked as expected! There is a bug in version 6.2.2 though.
Firebase JS SDK 6.2.3 was just released today, and it fixes this bug:
https://firebase.google.com/support/release-notes/js#authentication
Look like this is the git commit that fixes it:
https://github.com/firebase/firebase-js-sdk/commit/728f4f54b4589c07a2d474deb94328a332c8fe39
I verified it with this mocha unit test:
const firebase = require('../../firebaseApp')
const chai = require('chai')
describe('firebase javascript sdk', () => {
// This unit test verifies that the error message is as expected,
// and not the error "this.f is not a constructor", which was caused
// by a bug in version 6.2.1, and fixed in versin 6.2.3.
// https://stackoverflow.com/questions/56716255/how-to-fix-typeerror-when-using-signinwithcredential-on-node-js-edit-bug-in-f
it('should be able to checkActionCode', () => {
return firebase.auth().checkActionCode('xyz')
.catch(error => {
// https://stackoverflow.com/questions/56716255/how-to-fix-typeerror-when-using-signinwithcredential-on-node-js-edit-bug-in-f
chai.assert.equal(error.message,
"The action code is invalid. This can happen if the code is malformed, expired, or has already been used.")
})
})
})
The Firebase client SDKs generally do not work with nodejs. Firebase Authentication depends heavily on running inside a web browser in order to work correctly.
If you're running node, you might want to consider just using the Firebase Admin SDK to access your project without having to sign in.

Node.JS - firebase.auth() is not a function

I'm trying to use firebase Auth on a Node.JS server because Firebase Admin SDK doesn't implement all functions I need. Like firebase.auth.sendPasswordResetEmail(email).
But, when I try to get auth() I get following error:
let auth = fire.auth()
^
TypeError: fire.auth is not a function
My code is very simple:
let admin = require('firebase-admin');
let firebase = require('firebase');
const fire = firebase.initializeApp(config, "firebase");
let auth = fire.auth()
I'm, also, using Firebase Admin SDK for other functions and its auth() works fine.
There is some problem with use regular Firebase SDK on a Node.JS server?
EDIT:
I need both SDK because firebase-admin doesn't have functions like firebase.auth.sendPasswordResetEmail(email) or others.
Also, initializeApp is necessary for select the project in which I would operate.
Try deleting and re-installing node_modules. If the problem persists, you can add Firebase Authentication SDK to your script from the CDN:
<script src="https://www.gstatic.com/firebasejs/6.4.1/firebase-auth.js"></script>.
Refer here for the latest version: https://firebase.google.com/docs/web/setup

Google Firebase Web App - Error involving Cloud Functions and Firestore

Recently, I tried to follow a few demos online to get started on a Google Firebase Cloud Functions Node.js server-side code for an application. Upon attempting to add a Firebase App (and Firestore with it),
const functions = require('firebase-functions');
const firebase = require('firebase-admin');
require('firebase/firestore');
var serviceAccount = require("<private key>.json");
const initAppFirebase = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccount),
databaseURL: "<URL>"
});
var db = firebase.firestore();
I begin to get this one error that mentions a missing "annotations.proto" file from the google-gax module (which is apparently imported at some point in Firestore).
Error during trigger parsing: Error occurred while parsing your function
triggers.
Error: The include `google\api\annotations.proto` was not found.
at Function.GoogleProtoFilesRoot._findIncludePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:312:11)
at GoogleProtoFilesRoot.resolvePath
(C:\...\functions\node_modules\google-gax\lib\grpc.js:298:31)
...
at v1beta1 (C:\...\functions\node_modules\#google-
cloud\firestore\src\v1beta1\index.js:30:10)
at new Firestore (C:\...\functions\node_modules\#google-
cloud\firestore\src\index.js:229:18)
I have looked around on the internet, but nobody else seems to have this problem. I just reinstalled the files, but I am still getting this issue. Removing the Firestore and Firebase initializeApp code allows it to work, so I believe it has something to do with that.
Here are my module versions from package.json
"firebase-admin": "^5.12.0",
"firebase-functions": "^1.0.1",
"firestore": "^1.1.6",
Is there a way to fix this problem (botched installation, outdated libraries, missing code/requires etc.)? Thank you very much.
EDIT: Added code and package.json for version info. I dug around in the actual file \node_modules\google-gax\lib\grpc.js and found that it tries to return a valid path leading to the import file annotation.proto by trying to test google\api\annotations.proto at each parent directory.
var current = originPath;
var found = fs.existsSync(path.join(current, includePath));
while (!found && current.length > 0) {
current = current.substring(0, current.lastIndexOf(path.sep));
found = fs.existsSync(path.join(current, includePath));
}
if (!found) {
throw new Error('The include `' + includePath + '` was not found.');
}
return path.join(current, includePath);
There is, unfortunately, no such directory, though perhaps it is looking for the annotations file in google-proto-files\google\api\annotations.proto (but adding that file in manually leads to further errors). There is also a github issue here https://github.com/googleapis/nodejs-firestore/issues/175 mentioning it.
You say that you're trying to build a web app. But the code you are using is for initializing the Firebase Admin SDK in a (server-side) Node.js script.
If you want to use Firestore in your web app, start with the code you see when you click the WEB tab on this page:
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-firestore.js"></script>
And then:
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
You can get the values in that initializeApp call by:
Going to the Project overview page
Click ADD ANOTHER APP
Click Add Firebase to your web app

Google Cloud Functions, Node JS 8.9.x (LTS) and KOA library

How can I use Koa library, the express replacement, in Cloud Functions?
I know KOA use all great ES2017 and make more use of Async use of JavaScript.
or it might not be needed at all working with Cloud Functions because the Firebase system won't send multiple calls to the same Cloud Function until it ends the previous one?
it unclear to me.
it know demands Node 8.x and I know the NodeJs 8.9.x, has now LTS.
Reading from cloud functions doc:
Base Image Cloud Functions uses a Debian-based execution environment
and includes contents of the gcr.io/google-appengine/nodejs Docker
image, with the Node.js runtime installed in the version, specified
above:
FROM gcr.io/google-appengine/nodejs
RUN install_node v6.14.0
To see what is included in the image, you can check its GitHub
project, or pull and inspect the image itself. Updates to the language
runtime (Node.js) are generally done automatically (unless otherwise
notified), and include any changes in the definition of the base
image.
And I saw a pull request back in November 2017, adding Nodejs v8. Here's hoping it can finally land in Google Cloud Functions 🤞🏻
UPDATE: Google Cloud Functions now support Node.js 8 and even Python!
Referring to the release notes from Google... Cloud Functions Release Notes
Node version supported is still at v6, same for firebase. You need to wait awhile before they release it in v8. Am pretty sure they will move to v8 when v6 no longer supported, but hopefully earlier...
Use babel:
index.js:
----------=
'use strict';
require('#babel/register')
require('babel-polyfill')
const http = require('http')
const createApp = require('./app/app.js')
const handle = createApp().callback()
if (process.env.IS_LOCAL_DEPLOYMENT) {
// to use same code in local server
http.createServer(handle).listen(3000)
} else {
module.exports.http = (request, response) => {
handle(request, response)
};
}
app.js:
--------
'use strict';
const Koa = require('koa')
module.exports = () => {
const app = new Koa()
app.use(......)
return app
}
package.json
------------
"scripts": {
.
.
"start": "export IS_LOCAL_DEPLOYMENT=true && node index"
.
.
}
I just saw in Cloud Functions Console editor for one of my functions that Node 8 is now a runtime option. See screenshot:

Firebase Node.js admin SDK timeouts when trying to access Realtime DB

Using the Node.js admin SDK with Firebase Functions I get a timeout whenever I try to access the Realtime Database. This occurs only when testing a function locally (firebase serve --only functions,hosting) and when the default app is initialized using the functions.config().firebase.
This is a new behavior that started just a couple a days ago. However, if I try to initialize the default app with the serviceAccount.json file everything works as expected.
I'm using firebase-admin version 4.2.1 and firebase-functions version 0.5.9.
I wrote a straight forward http triggered function that fails due to timeout:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const db = admin.database();
exports.testDbConnection = functions.https.onRequest((req, res) => {
return admin.database().ref().once('value')
.then(function(snapshot) {
res.json(snapshot);
}).catch(function(error) {
res.json(error);
});
});
from the documentation
Always end an HTTP function with send(), redirect(), or end(). Otherwise, your function might to continue to run and be forcibly terminated by the system
see https://firebase.google.com/docs/functions/http-events#terminate_http_functions
This might depend on the firebase-tools version that you are using, but looks familiar to this Github issue
The solution for it is to either upgrade to the latest version of the CLI or use the workaround solution:
Go to https://cloud.google.com/console/iam-admin/serviceaccounts
Click “Create service account”, give it a name (e.g. emulator), give it the Project>Owner role.Check “Furnish a new private key”, pick “JSON”.
Save the file somewhere on your computer
Run export GOOGLE_APPLICATION_CREDENTIALS="absolute/path/to/file.json"
Run firebase serve --only functions

Resources