Firebase database is not a function - firebase

I am trying to run isomorphic react app, using Firebase functions-samples.
But can't get the firebase database and I get the error "firebase.database is not a function"
const firebase = require('firebase')
// Load the Firebase database module.
require('firebase/database')
// Initialize Firebase using a client-side config.
const firebaseConfig = require('./client/firebase-config.json')
firebase.initializeApp(firebaseConfig)
const getDb = (ref) => firebase.database().ref(ref)
// Error firebase.database is not a function
Modules versions:
"firebase": "^4.13.0",
"firebase-admin": "~5.12.0",
"firebase-functions": "^1.0.2",

It works well with firebase-admin
const firebase = require('firebase-admin')
const firebaseConfig = require('./client/firebase-config.json')
firebase.initializeApp(firebaseConfig)
const getDb = (ref) => firebase.database().ref(ref)

Related

Firebase callable functions fail

Many functions have started to fail intermittently with the following error even before the first line of code is executed:
FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Failed to parse access token response: SyntaxError: Unexpected token p in JSON at position 4"."}
It's been more than 5 five days since i had opened a bug issue with Firebase support and i still don't have any feedback.
Does anyone why this is happening and how it can be fixed?
Libraries used and their versions:
"firebase": "^8.2.9",
"firebase-admin": "^9.5.0",
"firebase-functions": "^3.1.0"
Initializations:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "..."
};
var firebase = require("firebase");
firebase.initializeApp(config);
In a Cloud Function, if you want to interact with the Firebase services (e.g. Firestore, Auth service, etc), you need to use the Admin SDK.
So, you need to load the firebase-functions and firebase-admin modules, and initialize an admin app instance from which you interact with the services, as follows:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
const firestoreDB = admin.firestore();
const authService = admin.auth();
// ...
// Examples:
// In a Cloud Function
return firestoreDB.collection("cities").doc("LA").set({
name: "Los Angeles",
state: "CA",
country: "USA"
});
// In another Cloud Function
return authService.updateUser(uid, {
email: 'modifiedUser#example.com',
phoneNumber: '+11234567890',
})
.then((userRecord) => {
// ...
// return ...
})
In other words, you don't need to do:
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "..."
};
var firebase = require("firebase");
firebase.initializeApp(config);
Also note this note from the doc:
In many cases, new features and bug fixes are available only with the
latest version of the Firebase CLI and the firebase-functions SDK.
It's a good practice to frequently update both the Firebase CLI and
the SDK with these commands inside the functions folder of your
Firebase project:
npm install firebase-functions#latest firebase-admin#latest --save
npm install -g firebase-tools

How To Access Cloud Storage In Cloud Functions

Am trying to access Firebase Cloud Storage in my Cloud functions but i keep getting the following error in the cloud functions log:
Error: Failed to import the Cloud Storage client library for Node.js. Make sure to install the "#google-cloud/storage" npm package. Original error: SyntaxError: Unexpected token {
at new FirebaseError (/srv/node_modules/firebase-admin/lib/utils/error.js:43:28)
at new Storage (/srv/node_modules/firebase-admin/lib/storage/storage.js:65:19)
at /srv/node_modules/firebase-admin/lib/firebase-app.js:255:20
at FirebaseApp.ensureService_ (/srv/node_modules/firebase-admin/lib/firebase-app.js:376:23)
at FirebaseApp.storage (/srv/node_modules/firebase-admin/lib/firebase-app.js:253:21)
at FirebaseNamespace.fn (/srv/node_modules/firebase-admin/lib/firebase-namespace.js:292:45)
at exports.initializeNewVideoUpload.functions.firestore.document.onCreate (/srv/index.js:383:24)
at cloudFunction (/srv/node_modules/firebase-functions/lib/cloud-functions.js:134:23)
at /worker/worker.js:825:24
at <anonymous>
Below is my code:
const admin = require('firebase-admin');
const functions = require('firebase-functions');
admin.initializeApp();
const db = admin.firestore();
exports.initializeNewVideoUpload = functions.firestore.document('new-videos-uploads/{id}').onCreate(async (snapshot, context) => {
const data = snapshot.data();
const fileNames = data.file_names;
const bucket = admin.storage().bucket('trumateappdev.appspot.com');
fileNames.forEach(async fileName => {
const actualFile = bucket.file(fileName);
const resumableUpload = await actualFile.createResumableUpload();
const uploadEndpointUrl = resumableUpload[0];
data.resumable_urls.push(uploadEndpointUrl);
});
await admin.firestore().collection('new-videos-uploads').doc(context.params.id).update(data);
});
Below are the dependencies in my package.json:
"#google-cloud/storage": "^5.5.0",
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0"
PS: Am on the Spark Plan
I found this solution here. Add this to your package.json:
"engines": {"node": "8"}
Apparently this problem occurs because your node.js version is too old

Using with Firebase / Expo query to Cloud Firestore

So I am trying to keep my code clean and build different files for querying... So I may be taking this harder than it needs to be.
I building a react-native app using Expo CLI.
I have created 3 files, one is my firebase config file,
one is a query file
then the actual file that is using that query.
it looks ok to me... but I get this error.
TypeError: undefined is not an object(evaluating'_firebase.firebase.firestore')
Here is my config file
import * as firebase from "firebase";
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "api-key",
authDomain: "project-id.firebaseapp.com",
databaseURL: "https://project-id.firebaseio.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "sender-id",
appId: "app-id",
measurementId: "G-measurement-id"
};
firebase.initializeApp(firebaseConfig);
Then I have a a query file, basically acting as the API layer
import { firebase } from "./firebase";
const db = firebase.firestore();
const getListings = () => {
db.collection("listings").get();
};
export default {
getListings,
};
Then I am trying to view the queried data.
import listingApi from "../api/listings";
function ListingsScreen({ navigation }) {
const [listings, setListings] = useState([]);
useEffect(() => {
loadListings();
}, []);
const loadListings = async () => {
const response = await listingApi.getListings();
setListings(response.data);
};
This is my first time ever using Firebase or cloud firestore... so im really confused.
The error message is telling you that '_firebase.firebase.firestore' data is returning as undefined, this means the document you requested doesn't exist.
At the officiald documentation of Expo, is recommended to put the firebase config information in the same file with your code in order to use firebase, for example:
import * as firebase from 'firebase'
import 'firebase/firestore';
const firebaseConfig = { ... } // apiKey, authDomain, etc. (see above)
firebase.initializeApp(firebaseConfig);
const dbh = firebase.firestore();
dbh.collection("characters").doc("mario").set({
employment: "plumber",
outfitColor: "red",
specialAttack: "fireball"
})

FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

Hey I am pulling my hair out on this one - I have read several posts here but keep getting this error here is my code for init.js
import firebase from "firebase/app"
var config = {
apiKey: "AIzaSyAF2VbjdWbQdsdsdk79nINQV5wdsdBn-uMy844gY7s",
authDomain: "lcarchivewebsite.firebaseapp.com",
databaseURL: "https://lcarchivewebsite.firebaseio.com",
projectId: "lcarchivewebsite",
storageBucket: "lcarchivewebsite.appspot.com",
messagingSenderId: "71812947145517",
appId: "1:718129478445517:web:0284d6bsdsdbb57384c87800c4"
};
firebase.initializeApp(config);
export const firestore = firebase.firestore()
export const db = firebase.database()
export const auth = firebase.auth()
export const storage = firebase.storage()
my component is here:
<template>
<h2>hello</h2>
</template>
<script>
import storage from 'firebase'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
created(){
var storageRef = storage.storage().ref()
var listRef = storageRef.child('2020')
listRef.listAll().then((response) => {console.log(response)})
}
}
</script>
i have installed firebase with npm install --save
here is package.json
"dependencies": {
"firebase": "^7.17.1",
"materialize-css": "^1.0.0",
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"webpack-cli": "^3.3.12"
},
Couple of problems here, the first being that you are importing from the firebase lib in node_modules where you should be importing the storage you exported from your init.js script.
Fix this with
import { storage } from '#/path/to/init.js' // "#" refers to your "src" directory
// snip
var storageRef = storage.ref()
The other problem is that in order to use Firebase features like storage, you need to import those libs. So in init.js...
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/database'
import 'firebase/firestore'
import 'firebase/storage'

React native cloud functions logs empty

I was trying cloud functions today, followed the docs and got it to deploy successfully but the logs will always be empty.
I am using RN firebase client SDK from this website
https://rnfirebase.io/docs/v5.x.x/functions/reference/functions
"dependencies": {
"firebase-admin": "^7.0.0",
"firebase-functions": "^2.2.0",
}
This is my function code :
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
//
exports.helloWorld = functions.https.onRequest((request, response) => {
console.log('hello world');
response.send("Hello from Firebase yo!");
});
this is my dashboard screen shot:
this is my logs screen shot:
Did i miss anything ?

Resources