'Firebase Not Defined' An Answer For Version 9 Of Firebase - javascript

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.

Related

Firebase creating custom token using spotify signin?

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.

I'm gettin error default.storage is not a function when i run my react app

I'm trying to implement adding images feature in my react project with usage of firebase storage.
This is the error:
Uncaught TypeError: firebase_compat_app__WEBPACK_IMPORTED_MODULE_3__.default.storage is not a function.
This error occurs in firebase configuration file. I used firebase firestore in this project for adding new blogs, and I was adding images through url and everything worked just fine.
Here are my imports:
import firebase from 'firebase/compat/app';
import "firebase/storage"
And instance of storage
export const storage = firebase.storage()
When using the compatibility library, make sure that all components are imported from the compatibility library.
import firebase from 'firebase/compat/app';
import "firebase/compat/storage";
// ^^^^^^
The compatibility library is for supporting legacy code. For all new code, you should be using the modern Modular SDK because the legacy Namespaced SDK is deprecated. See the upgrade guide for details.
If you are an expo user importing firebase from compat/storage solves the issue
import firebase from 'firebase/compat/app';

Trouble with firebase imports when upgrading to version 9

I tried to move over to the firebase version 9 and I updated all my imports without changing the code and now when I try to do my google sign in I keep on getting this
TypeError: Cannot read properties of undefined (reading 'GoogleAuthProvider')
This is the code that I am having a problem with
import firebase from "firebase/compat/app";
const provider = new firebase.auth.GoogleAuthProvider();
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
firebaseConfig
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export default app
I would like to suggest you read the guide to update to Firebase v9 from v8, as I see you confirmed earlier you have only updated your imports, but I'm afraid you will need to do some extras to get your code completely upgraded, even though you mentioned you had issues with Authentication, and one of the main steps is to remove compat code from the previous version, especially in that module. Here are the steps:
About the upgrade process
Each step of the upgrade process is scoped so that you can finish editing the source for your app and then compile and run it without breakage. In summary, here's what you'll do to upgrade an app:
Add the version 9 libraries and the compat libraries to your app.
Update import statements in your code to v9 compat.
Refactor code for a single product (for example, Authentication) to the modular style.
Optional: at this point, remove the Authentication compat library and compat code for Authentication in order to realize the app size benefit for Authentication before continuing.
Refactor functions for each product (for example, Cloud Firestore, FCM, etc.) to the modular style, compiling and testing until all areas are complete.
Update initialization code to the modular style.
Remove all remaining version 9 compat statements and compat code from your app.
You are receiving this error because the code you are using to initialize GoogleAuthProvider is from v8, so please substitute it with the following code as suggested by the official documentation:
import { GoogleAuthProvider } from "firebase/auth";
const provider = new GoogleAuthProvider();
If you follow the previous guide missing steps, probably the error will be gone
Finally, I see you have firebaseConfig under your import, and I'm not sure if you are really calling it like this, but I would follow the updated guide.
import { initializeApp } from 'firebase/app';
firebaseConfig = {
//...
};
const app = initializeApp(firebaseConfig);

How can I use Firebase 9.x + Flow

I'm working on a NextJS project using Flow and I'm trying to import Firebase latest version 9.1.3, but when I try to use it, Flow complains that cannot find the module.
// Error: Cannot resolve module `firebase/app`.Flow(cannot-resolve-module)
import { initializeApp, getApps } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
I only found an old solution on flow-typed for Firebase 5.x.x, but API has changed since then, and manually writing a Library Definition is super time consuming.
I noticed that Firebase uses Typescript, is there a way I can import/convert to use Flow?
No flow types and TS types are not compatible although they achieve the same goal they are different in their typing philosophy.
Regarding firebase types, because firebase doesn't use flow, flow-typed is the correct place to retrieve them if the existed but no one has done so for firebase types for a while.
I have personally made a start in a project I started a while back but you may need to add more to suit your usecase (firebase types in my project). If these suit your usecase as a base I'm happy to commit them into flow-typed but I'll just need to include some tests.

Using Firebase with Webpack and TypeScript

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

Categories

Resources