I'm following along with this talk from google. However I can't instantiate a firebase object.
I have a package.json file and started with:
npm install firebase --save
Then did the following:
let Firebase = require('firebase');
let myFire = new Firebase('[link to my app]');
However, when I run the johhny-five app from terminal, I get the error: Firebase is not a function.
How am I supposed to intstantiate the object? Did Firebase change their API?
Note: I injected it into the repl and running >> typeof Firebase I get that it's actually an 'object'.
Yes, they changed the API, take a look: Upgrade your Web / Node.js app from Firebase.com.
This is how you do it now:
// See https://firebase.google.com/docs/web/setup#project_setup for how to
// auto-generate this config
var config = {
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com"
};
firebase.initializeApp(config);
var rootRef = firebase.database().ref();
To get the config values, go to the URL at the top of the previous code, Add Firebase to your Web Project, which guides you to do the following:
To add Firebase to your app, you'll need a Firebase project and a short snippet of code to add to your application HTML that has a few details about your project.
Create a Firebase project in the Firebase console, if you don't already have one.
If you already have an existing Google project associated with your app, click Import Google Project. Otherwise, click Create New Project.
If you already have a project, click Add App from the project overview page.
Click Add Firebase to your web app.
Click Copy, then paste the code snippet into your application HTML.
Related
I am trying to implement a 'Log in with Spotify' feature for my react app. I am trying to follow this blog but I am not able use
firebase.auth().createCustomToken(uid)
as i get the error
.createCustomToken is not a function
I also tried using firebase-admin package but I run into
Can't resolve util in /node_modules/#google_cloud/common/build/src
This is what I have tried to do so far. I have never used firebase before. Any help would be appreciated.
import {getAuth} from 'firebase-admin/auth';
import { initializeApp } from 'firebase-admin/app';
import admin from 'firebase-admin';
var serviceAccount = require('./service-account.json')
const spotifyApi = new SpotifyWebApi();
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
let uid= 5;
getAuth().createCustomToken(uid).then(function(customToken) {
console.log(customToken);
});
The blog post you're following is a few years old, and recent versions of the Firebase SDK for JavaScript have switched to a different syntax (to allow build tools to automatically exclude unused parts of the SDK from you app bundle).
What used to be:
firebase.auth().createCustomToken(uid)...
Is now accomplished with:
createCustomToken(getAuth(), uid)...
For more on this, I recommend also checking out the upgrade guide for the new v9 SDK.
Update: as Dharmaraj commented below createCustomToken is still a method on the auth object.
Im trying to make a database call/post but im getting the error
functions.js:7 Uncaught ReferenceError: firebase is not defined
From my research it is my understanding that 'firebase' is defined in the firebase.js script file that is imported using the CDN code from the setting panel in Firebase..
But all the help pages i find are from 2014-2017 and version 9 of Firebase uses a completely different import language.. These pages are no help to me..
I am using the standard
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
Am I right in thinking that because this import is happening (and its seemingly is - firebase-app.js is showing up in the inspector) That firebase should be defined...
Or is firebase defined somewhere else and im missing something??
If this is the case where is firebase defined and how do i import it (with V9 Firebase)
Thanks
Edit: Im doing this all through a tutorial I found on Youtube, its from 2019.. Is it possible that calling upon 'firebase' now is outmoded and that is what I am having these troubles? Or should i expect it to work and keep trying to find a solution?
In v8 and older versions of the Firebase Web SDK, now referred to as the "namespaced SDK", the SDK would add methods and types to a global object called firebase. You will see a lot of existing tutorials with code that looks like firebase.initializeApp(), firebase.database() and firebase.firestore.FieldValue.increment(). All of these calls will not work in the newer versions of the Firebase Web SDK.
In v9 and later versions of the Firebase Web SDK, now referred to as the "modular SDK", the SDK undertook a major architectural revamp and introduced lots of breaking changes. The primary change with the new version is that the firebase global object was completely removed and every method and type is now exported independently. When using this new SDK with a build tool like Webpack or Rollup, it can "shake the tree" to loosen and remove all of the bits of code that you don't actually use in your code from the final build.
As an example, if you don't use any of the FieldValue transforms in your code (like increment(), serverTimestamp() and arrayUnion()) they won't be included in your final build saving you and your users resources and time.
Not sure how you are using the script files, but have u defined them as "modules" in you html like:
and have you initialized firebase from your app:
const firebaseConfig = {
YOU_FIREBASE_CONFIG
}
const app = initializeApp(firebaseConfig)
The difference between v8 and v9 of firebase is a well-known error these days.
I am not sure this could be the exact solution, but at least as a hint.
Using compat is a way to solve.
Based in the firebase document below.
import firebase from 'firebase/compat/app';
↑would be how to import.....
Upgrade from version 8 to the modular Web SDK
When you run this code:
import { initializeApp } from ...
This code imports only the initializeApp function, and nothing else. That's precisely its point, because by using these very granular imports, bundler tools (like webpack) are able to drop any part of the Firebase SDK that you are not using from their output, resulting in a significantly smaller app.
So when you run that import, there is no top-level firebase namespace anymore. To access the Realtime Database, you'd instead use:
import { initializeApp } from 'firebase/app';
import { getDatabase } from "firebase/database";
// Set the configuration for your app
// TODO: Replace with your project's config object
const firebaseConfig = {
apiKey: "apiKey",
authDomain: "projectId.firebaseapp.com",
databaseURL: "https://databaseName.firebaseio.com",
storageBucket: "bucket.appspot.com"
};
const app = initializeApp(firebaseConfig);
// Get a reference to the database service
const database = getDatabase(app); // 👈 Get the database instance
This is shown in the documentation on initializing the Realtime Database JavaScript SDK, so I recommend keeping that handy.
If you're following a tutorial or documentation from elsewhere, it likely hasn't been updated to the new modular syntax yet. You can also use the compat mode of the new SDK in that case, as user K Lee pointed out in their answer.
After a while I realized that all your Javascript code has to be run within the SDK module tags that you import from the Firebase Dashboard...
If your Javascript is not run within the <script type="module"> tags from the imported Firebase code the imported modules from Firebase's modular SDK wont be defined.
Also I was trying to go through a tutorial that was from V5 of Firebase and was running into problems there as well.
I used a firebase package for using realtime DB and I want to implement firebase analytics so I used the same package and write code for analytics
import * as firebase from 'firebase'
import 'firebase/analytics'
import { fireBase } from 'configs/config'
const config = {
apiKey: fireBase.REACT_APP_FIREBASE_API_KEY,
authDomain: fireBase.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: fireBase.REACT_APP_FIREBASE_DATABASE_URL,
projectId: fireBase.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: fireBase.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: fireBase.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: fireBase.REACT_APP_FIREBASE_APP_ID,
measurementId: fireBase.REACT_APP_MEASUREMENT_ID,
}
firebase.initializeApp(config)
export const defaultAnalytics = firebase.analytics()
export default firebase
after that, I imported defaultAnalytics in the file where I needed it and put that code to log the event for analytic purposes
defaultAnalytics.logEvent('profile_update')
It is working in development perfectly but not working in the production mode
There is issue like in electron, When we run app in development mode it will log firebase event easily because the app is run on localhost:3000 so a event will work.
But when we create a build for mac/windows it will not log the event because firebase package work when a build run on http protocol and our electron app production build run a file:// protocol.
So here we have to use Measurement Protocol, In that we need to create a separate property in firebase app.
Steps for creating a property:
Go to analytics.google.com then create a firebase app.
click on Create property and choose website option.
The provide a website URl and name of property name.
After the you will get a tracking info.In that a tracking code will be available.
Then use universal-analytics in main Processes.
Here is the complete implementation.
https://kilianvalkhof.com/2018/apps/using-google-analytics-to-gather-usage-statistics-in-electron/
I am using webpack to compile a preact / firestore application, and firebase overall is contributing 1.7 MB to the size of my compiled bundle. I am attempting to reduce this number.
The realtime database and storage together contribute about 750 kb to the bundle size. As I am not using the realtime database and storage at all, I would like to be exclude these from the bundle. I suspect, but am not certain, that if I stop calling
import firebase from 'firebase';
require("firebase/firestore");
and instead do something to the effect of
import auth from 'firebase/auth';
require("firebase/firestore");
that this would remove the unwanted submodules from my bundle. But, I can't get rid of my firebase import right now, as I am calling
firebase.initializeApp(config);
as per the documentation. Can I initialize firestore without calling firebase.initializeApp?
The web setup page for Firebase tells you what is optional and required:
You can reduce the amount of code your app uses by just including the
features you need. The individually installable components are:
firebase-app - The core firebase client (required).
firebase-auth - Firebase Authentication (optional).
firebase-database - The Firebase Realtime Database (optional).
firebase-firestore - Cloud Firestore (optional).
firebase-storage - Cloud Storage (optional).
firebase-messaging - Firebase Cloud Messaging (optional).
You need to call initializeApp() no matter which parts of Firebase you intend to use. That call indicates which project is in use.
The last example from the documentation on adding Firebase to your app shows how to do this:
var firebase = require("firebase/app");
require("firebase/auth");
require("firebase/firestore");
var config = {
// ...
};
firebase.initializeApp(config);
As Doug says, initializeApp(...) is always needed.
I'm trying to pull some data from a Firebase instance, but am running into an issue when trying to bind it to a variable. I'm using TypeScript and Webpack to build.
main.ts
import * as Firebase from 'firebase';
class filter {
constructor(){
let ref = new Firebase('my-url-here');
}
}
The typings and npm module are installed and working, and Visual Code brings up no errors, but when I hit the browser I get:
ERROR
TypeError: Firebase is not a constructor
..
Logging Firebase to the console returns an object with methods like auth, app and database, but none of these seem to work either (or I'm calling them incorrectly). Any ideas?
A general best practice on how to incorporate Firebase into a Webpack/TypeScript would be just as welcome.
In my project i had the same error: It was caused by the firebase.json file which i guess got picked up by webpack.
As i can only guess why it happened: Webpack creating a symbol "Firebase" which replaced the constructor of firebase itself.
Have you done a firebase init in your directory?
Also see : https://github.com/angular/angularfire2/issues/187