firebase.database() is not a function on local node - node.js

I'm running a simple node app in my local machine and I need to connect to firebase realtime database.
I installed firebase via npm:
npm install firebase --save
Then I initialize the app:
var firebase = require("firebase");
var config = {
apiKey: "api-key",
authDomain: "my-app-database.firebaseapp.com",
databaseURL: "https://my-url.firebaseio.com",
storageBucket: "my-app-database.appspot.com",
};
firebase.initializeApp(config);
var myRef = firebase.database().ref("collection").on("value", (snap) => {
// do something with the data
});
Then I get the error that database is not a function. I check firebase.database and is undefined, also so are firebase.auth and firebase.storage.
I followed all the steps in the docs, but I don't see anything that could be causing this.

Goodness gracious... It was as simple as requiring the other packages in the file, like this:
// firebase
const firebase = require("firebase");
// get database, auth and storage
require("firebase/auth");
require("firebase/storage");
require("firebase/database");
Nowhere in the docs or reference says that. I thought about going back a version, perhaps 4.12.x, so I went to the npm page to see the previous versions and install one of those and try, when I found this:
https://www.npmjs.com/package/firebase#include-only-the-features-you-need
Just scroll down where they mention using npm packages or Typescript and you'll find the answer.
Shout out to the Firebase team, this information can't be just in the npm page and not in the docs, getting started guides or the github repo. Not a lot of people goes to the npm page of a package for information and I went there to check previous versions, so I kind of stumbled upon it.

Related

Integrate Cloud Functions for Firebase with Braintree

I'm trying to see if it's possible to integrate Cloud Functions for Firebase with Braintree. I created a project for Cloud Functions according to the docs.
In the project directory I ran: npm install braintree.
I modified index.js for testing purposes to be the following:
const functions = require('firebase-functions');
var braintree = require("braintree");
var gateway = braintree.connect({
environment:
braintree.Environment.Sandbox,
merchantId: "useYourMerchantId",
publicKey: "useYourPublicKey",
privateKey: "useYourPrivateKey"
});
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-
functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
response.send("Hello from Firebase!");
//gateway.clientToken.generate({}, function (err, response) {
//response.send(response.clientToken);
//});
});
When I tried to deploy this test function I got the error
Error parsing triggers: Cannot find module 'braintree'
I'm new to Firebase, Cloud Functions, and node.js and would appreciate any input on how to import Braintree to Firebase Functions project.
It looks like Cloud Functions for Firebase is not picking up the braintree module. Like most Node.js environments, Cloud Functions reads the dependencies from package.json. When you install a module with npm you can tell it to also write it to package.json by adding --save to the command line. So:
npm install braintree --save
You have the Node.js package braintree missing.
Your Firebase project has a directory called functions.
In the terminal, go to the functions directory by $ cd {your project dir}/functions
And then npm i braintree --save.
I hope that it helps you.
change current directory to functions:- cd functions
then install braintree in that folder using npm: - npm i braintree
then import braintree : - var braintree = require('braintree');
now everything should work fine.
Note:- if you have not enabled payment in firebase, it will though 'unexpectedError' in the http response.

Firebase -Node.js auto complete doesn't show .auth() or it's accompanying methods

I'm running Node version 7.8.0
I have installed the Firebase and Firebase-admin modules into a Server side Node.js app.js file. I want to use these 2 methods:
var myCustomToken = '12345'
firebaseAdmin.auth().createCustomToken(myCustomToken) //firebaseAdmin.auth()
firebase.auth().authenticateWithCustomToken(myCustomToken) // firebase.auth()
The problem is dot .auth() doesn't show up for either module so I can't get to use the 2 methods. There are other methods that are tied to both modules that appear (in pics below) but .auth() isn't one of them.
For e.g.
firebaseAdmin.initializeApp(... //works
firebaseAdmin.credential.cert(... //works
firebase.initializeApp(...) //works
These are the modules I installed in the folder that was initialized with npm:
npm install firebase-admin --save
npm install algoliasearch --save
npm install firebase --save
These are the dependencies inside my package.json file:
"engines": {
"node": "7.8.0"
},
"dependencies": {
"algoliasearch": "^3.22.1",
"firebase": "^3.7.4",
"firebase-admin": "^4.1.4"
}
How can I get .auth() to appear on each module so I can access the 2 methods I need?
Firebase-admin module autocomplete:
Firebase module autocomplete:
Autocomplete results for both modules .auth() doesn't exist:
Have a look at https://firebase.google.com/docs/admin/setup
and https://firebase.google.com/docs/auth/admin/create-custom-tokens#create_custom_tokens_using_the_firebase_admin_sdk
for createCustomToken()
As for the client part, did you try signInWithCustomToken() ?
I filed an issue report at the Firebase-admin github repo and they got back to me and said that even though the .aut() object isn’t showing up in Sublime’s autocomplete it does exist. Since I knew the methods I was looking they said I could just manually put in the code and it would work which in fact it did.
One thing they suggested was that next time I can go into the node_modules folder and I would see that it does exist there:
node_modules/firebase-admin/lib/firebase-namespace.js
this is what is there:
Object.defineProperty(FirebaseNamespace.prototype, "auth", {
/**
* Gets the `Auth` service namespace. The returned namespace can be used to get the
* `Auth` service for the default app or an explicitly specified app.
*/
get: function () {
var _this = this;
var fn = function (app) {
return _this.ensureApp(app).auth();
};
return Object.assign(fn, { Auth: auth_1.Auth });
},
enumerable: true,
configurable: true
});
Basically if your using Sublime and autocomplete isn’t showing what your looking for just manually type it in and look through the node_modules folder to verify it’s there.
Another alternative is to use VSCode or Vim instead of Sublime and the autocomplete should work there.

FireStore - TypeError: k.setTimeout is not a function

I'm using Firebase in a React Native app and authentication with a facebook token. It works fine with RealTime Database.
But not Firestore. When I call collection.get, set or add I got this error which is not caught by my handler but just dumped in the console.
(node:15795) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: k.setTimeout is not a function
I tried also as a standalone script run as node t_firebase.js.
I installed the packages with
npm install firebase
npm install firestore
I'm using node v6.11.4 and npm 3.10.10, firestore 1.1.6, firebase 4.5.1
Here is the script:
var firebase = require("firebase");
require("firebase/firestore");
var config = {
apiKey: "...",
authDomain: "....firebaseapp.com",
databaseURL: "https://....firebaseio.com",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
testFirebase();
function testFirebase(){
console.log("testFirebase");
token="...";
var credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase.auth().signInWithCredential(credential)
.then(function(val){testFirestore();})
.catch((error)=>{console.log("error:"+error);});
}
function testFirestore(){
console.log("testFirestore");
var db = firebase.firestore();
var collection = db.collection("livros");
var docref = collection.add({
autor: "AdaLovelace",
name: "blabla"
}).then(function(val){ console.log("OK"); }).catch((error)=>{console.log("error:"+error);});
}
Although you mention React Native, your error is actually from node.js so I'm not certain which environment you're asking about.
React Native - The "firebase" npm module does not currently work with React Native due to a bug. See https://github.com/firebase/firebase-js-sdk/issues/183 for more details and workarounds.
Node.JS - You can use Cloud Firestore from Node.JS using the "firebase-admin" SDK. See the node.js snippets on https://firebase.google.com/docs/firestore/quickstart for more details. Cloud Firestore is not currently supported via the "firebase" SDK, but this is planned in the future. See https://github.com/firebase/firebase-js-sdk/issues/221 for more details.

Firebase Node.js SDK unauthenticated access

I am trying to access Realtime Database using the new feature introduced with 3.1.0 release: "The Node.js SDK now supports unauthenticated access. If no service account is provided, Realtime Database access will be restricted just as any unauthenticated client would be."
The SDK is updated to 3.1.0:
user#ha:~/dev/project/auth/firebase$ sudo npm install -g firebase
[sudo] password for user:
/usr/local/lib
└─┬ firebase#3.1.0
Tried with no service account:
var firebase = require('firebase');
console.log('Initialise Firebasse app');
firebase.initializeApp({
// serviceAccount: "",
databaseURL: "https://some-valid-firebase.firebaseio.com"
});
The result is:
user#ha:~/dev/project/auth/firebase$ nodejs fb_anon.js
Initialise Firebasse app
/home/user/dev/project/node_modules/firebase/auth-node/auth.js:61
throw new Error('Invalid service account provided');
^
Please help, probably I am missing something obvious here. :-(
What is happening is that your application is referring to an old sdk version that is inside your node_modules. And thats because you updated the firebase sdk with the globally flag and you are referring to a local sdk.
You should be installing it locally to your application.
First make sure you added "firebase":"3.1.0" into your package.json file and then call npm install inside the same dir.
I've just tested it with the same piece of code you added and everything went as expected.
In this question you can find some additional information and tips when using npm.

Firebase reference is empty after requiring new version

The new documentation provides a straightforward method of initialising firebase, for example, this snipped comes directly from the README.md file:
Install the Firebase npm module:
$ npm init
$ npm install --save firebase
In your code, you can access Firebase using:
var firebase = require('firebase');
var app = firebase.intializeApp({ ... });
// ...
But in my installation this is not working, as in, firebase is empty ({} when console logged).
There's another section in the documentation called Include only the features you need, which provides the following snippet:
var firebase = require('firebase/app');
require('firebase/auth');
require('firebase/database');
var app = firebase.initializeApp({ ... });
// ...
This method works for me, so I'm wondering what could I be doing wrong in the first instance?
I'm using browserify, if that helps, but the docs state: The browser version is designed to be used with
a package bundler (e.g., Browserify,
Webpack).

Resources