I am in the middle of creating a simple library app. Here, I am trying to use firestore database in firebase console. I am coding this on the expo snack editor. It does not work.
here is a screenshot of the error in the snack editor:
These 2 lines are definitely causing the error:
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
PS this is the firebase version 9 sdk
this is my package.json in snack editor:
EDIT: I forgot to mention that this exact code on snack is working fine in VS Code locally.
to get a working example of code locally:
go to this link: https://snack.expo.dev/#rpshende/e-library-app
Then,
Extract the folder
cd to the folder in terminal
run command 'npm install'
then run command 'expo start'(make sure expo cli is installed for this to work!)
when the expo developer tools are fired up, press 'W' on the terminal to open project in a web browser
EDIT: i think this is a problem with the snack editor itself.....
As #whitehatcoder says, in the expo bubble editor there are version differences. Firebase should have been on version 8 instead of 9.
I add that you try this
{
"dependencies": {
"firebase": "8.8.1"
}
}
Firebase v9 is Different
try this
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { getAuth, GoogleAuthProvider , signInWithPopup, } from 'firebase/auth';
const firebaseConfig = {
apiKey: "AIzaTyD2Jp9aB7ycUbW1z8QyPLmD111rHezHcOw",
authDomain: "delete-project-c7021.firebaseapp.com",
projectId: "delete-project-c7021",
storageBucket: "delete-project-c7021.appspot.com",
messagingSenderId: "688102987186",
appId: "1:688102987186:web:e27537ggg7abc2b86b982b"
};
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const auth = getAuth();
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);
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.
In my reactjs project I have installed firebase using 'npm i firebase'. And inside of src folder I have created firebase.js file for firebase config.
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "******",
authDomain: "****",
projectId: "***",
storageBucket: "*****",
messagingSenderId: "****",
appId: "****"
};
firebase.initializeApp(config);
export default firebase
Even after installing firebase in my project. It gives error:
./src/firebase.js
Module not found: Can't resolve 'firebase' in '/home/rupak/Projects/web/firebasereact/src'
Can anyone find the problem?
You are not using the new Modular syntax. You can keep using existing code by changing the imports to compat version:
import firebase from 'firebase/compat/app'
import 'firebase/firestore'
// import 'firebase/[SERVICE_NAME]'
However, I'd recommend upgrading to the new Modular SDK, which offers some benefits with tree-shaking. Checkout this Firecast for detailed information:
Getting started with Firebase for Web
Refer Firebase docs if you are using newer version initializeApp is moved to firebase/app package
Hey I had the same situation stated above...
But by applying this:
import firebase from 'firebase/compat/app'
import 'firebase/firestore'
// import 'firebase/[SERVICE_NAME]'
//export
export const auth = firebase.auth();
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();
I only removed the (/app), and it worked... THANK YOU
I have faced the same issue, It seems firebase 9.17.0 just dropped.
Rolling back to the 9.16.0 solved the problem.
for yarn package:
yarn add firebase#9.16.0
for npm:
npm i firebase#9.16.0
Now check your package.json file looks like this.
"firebase": "9.16.0",
I am using Webpack with firebase and firebase-admin.
To install firebase I ran:
npm install --save firebase
I am importing firebase using:
import * as firebase from 'firebase/app'
import 'firebase/auth'
I also tried:
import * as firebase from 'firebase'
And I tried:
const firebase = require('firebase')
As suggested in web get started guide.
However, when I try to use firebase.auth() I get an error:
console.js:32 TypeError: firebase.auth is not a function
When I use the debugger to inspect firebase I see that it in fact does not have an auth function:
> firebase
{__esModule: true, initializeApp: ƒ, app: ƒ, Promise: ƒ, …}
How can I get auth() included as a function using webpack?
I fixed this by deleting my node_modules directory and reinstalling everything.
Also I'm importing firebase like so:
import firebase from 'firebase'
require('firebase/auth')
The problem wasn't with the node_modules, it was with the way that you were importing the component.
When you export a component ES6 way, you normally do export default () => { console.log('default component export'); };
default is the keyword here, when you import a component ES6 way like import firebase from 'firebase' it's grabbing the default property from the exported object.
Keeping in mind the above example, here's what you've done wrong.
Using ES6:
import * as firebase from 'firebase'
console.log(firebase.auth) // Undefined
console.log(firebase.default.auth) // Function
Using ES5:
var firebase = require('firebase')
console.log(firebase.auth) // Undefined
console.log(firebase.default.auth) // Function
Note the .default
I kept getting an error that said
"TypeError: firebase.auth is not a function"
I got the auth object to appear and the thing I did differently was install the modules in a different order.
The first time I installed the modules (this is when the auth object wasn't appearing):
// this seems to confuse things with the auth object when installed in this order
$ npm install firebase-admin --save
$ npm install firebase --save
I deleted the npm folder and started from scratch although this time I reversed the installation order:
// for some reason this worked and now I can access the auth object
$ npm install firebase --save
$ npm install firebase-admin --save
I didn't do anything else. I simply reversed the installation order by installing firebase first and firebase-admin second.
I hope this works for other people.
You can read more about it here
just add >
import firebase from '#firebase/app';
require('firebase/auth');
into your project
this is the import statement from official docs:
// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
// Add the Firebase products that you want to use
import "firebase/auth";
console.log(firebase.auth);
These also seem to work if you only want auth:
Edit: The code below worked with Firebase 7 package but not any more with version 8. It will change again for Firebase 9. Just stick to the docs and you will be fine.
import { auth } from "firebase/app";
import "firebase/auth";
console.log(auth);
or
import { auth } from "firebase";
console.log(auth);
Though there are many root causes behind this issue, a simple one like this also could be the case.
I forgot to include the js files for auth and db although I use them inside the JS code.
Before the fix;
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-app.js"></script>
After the fix;
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-app.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-database.js"></script>
You just need to use the import as following
import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
in the above case, both auth and DB services are being used.
For any other service, you need to import like that only.
This is because firebase-auth script is not added.
First you have to install npm files in your node modules by
npm install firebase --save
npm install firebase-admin --save
Then you have to add the script of firebase.auth after firebase-app script and make sure the version is same.
Before fix:
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js"></script>
AFTER FIX YOU NEED TO ADD BOTH THE SCRIPT AND AFTER THIS ADD YOUR FIREBASE ACCOUNT SCRIPT AS FOLLOWS
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-auth.js"></script>
THEN IT SHOULD WORK FINE
The main reason for this error could be due to the latest Firebase version v9.1.1, in this version the Firebase imports have been changed.
Before: version 8
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
Check docs here: https://firebase.google.com/docs/web/modular-upgrade
With firebase v9 you can not use auth like that anymore. Instead of that you need to import auth from "firebase/auth" like:
import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
and if you need to export auth object
const auth = getAuth();
export { auth };
if you need to use createUserWithEmailAndPassword function
createUserWithEmailAndPassword(auth, email, password)
You can check the official documentation for more
https://www.npmjs.com/package/firebase
When running in Node and needing both firebase and firebase-admin this works for me:
First install firebase and then firebase-admin in that order.
Then use as so:
const app = require('#firebase/app');
require('#firebase/auth');
require('#firebase/firestore');
const firebase = app.firebase
firebase.initializeApp({…})
const auth = firebase.auth()
const db = firebase.firestore()
Firebase 8 introduced some breaking changes.
https://firebase.google.com/support/release-notes/js#version_800_-_october_26_2020
Now you can make it work like this if you use .default:
const firebase = require('firebase/app').default
require('firebase/auth')
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const auth = firebase.auth()
In Firebase V9's JS SDK, thanks to Typescript, what I did is below:
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
async login = (email: string, password: string) => {
await signInWithEmailAndPassword(getAuth(), email, password)
}
I ran into this as well. My issue was the npm module #firebase was installed as well as the firebase module. When I required firebase in my JavaScript code with ‘require(“firebase”)’, webpack bundled #firebase instead for some reason.
#firebase doesn’t include auth, database etc. by default...it’s modular so you can require them separately. Consequently I received the above error when I tried calling auth().
To fix it you can remove #firebase...or just add the full path to the correct firebase when you require it like
require(‘/path/to/node_modules/firebase/firebase.js’)
Had the same issue, I think it's because of versions troubles.
I solve it by deleting node_modules and all webpack generated stuff and take versions from here.
Btw, I think it's very strange behavior, because it should work like in official documentation.
I ran into the same problem. However I didn't have to do any deletion of any files, just correct the import statements. In my case I use Firebase version 7.7.0 in an Gatsby/React app and this is what the import looks like:
import React from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';
const config = {
apiKey: process.env.GATSBY_FIREBASE_API_KEY,
authDomain: process.env.GATSBY_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.GATSBY_FIREBASE_DATABASE_URL,
projectId: process.env.GATSBY_FIREBASE_PROJECT_ID,
storageBucket: process.env.GATSBY_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.GATSBY_FIREBASE_MESSAGING_SENDER_ID,
};
class Firebase {
constructor() {
firebase.initializeApp(config);
this.auth = firebase.auth();
this.uiConfig = {
signinOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.FacebookAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID,
],
};
}
}
export default Firebase;
const FirebaseContext = React.createContext(null);
export { FirebaseContext };
Update after request from #Mel. The context may be used using either a HOC:
export const withFirebase = Component => props => (
<FirebaseContext.Consumer>
{firebase => <Component {...props} firebase={firebase} />}
</FirebaseContext.Consumer>
);
or using a hook:
import { FirebaseContext } from './firebase';
const MyComponent = () => {
const firebase = useContext(FirebaseContext);
// do something with firebase
};
This may solve the issue, try this >>>
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
const firebaseConfig = { };
const firebaseApp = firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
export { auth, provider };
most probably you forgot to put 'new' in this line --->
const provider = new firebase.auth.GoogleAuthProvider();
check again.
What-up. I ran into this while working through William Candillon's Adding Firebase To React Native tutorial...
Thoughts: There is a lot to love about Firebase. But the import/export, named vs default and versioning seems to bring a lot of people a lot of unnecessary heart-ache. <-- I say that with tears streaming down my face and a hole in my heart where a love of mobile development & unhappy childhood used to exist mere hours ago.
Put simply: I had firebase.auth is not a function.
Went hunting though node_modules, deleted, re-yarn'd, read blogs, tried importing as named then default, requiring separate modules a-la require('firebase/auth'); under the default import of firebase itself etc etc etc (it really shouldn't be this hard). Also, why do Google not have react documentation? It's 2018. Are people seriously still putting HTML script tags in their front end?
Current Solution => in the end I pulled all my config and firebase.initializeApp(config) into my top level app.js. I'll have to find time later to figure out why the "#firebase" module of auth can't be imported. Or why thats even there? Do i need it? Why isn't it all wrapped into the 'yarn add firebase' module?
Anyway - that'd be my advice. Get it working at top level first. Then hive-off the credentials into a separate file later. That and "Dont drink lager. It bloats-you-out and IPA is infinitely nicer."🍺🍺🍺
I had the same problem and solved it this way:
<script src = "https://www.gstatic.com/firebasejs/6.5.0/firebase-app.js"> </script>
<script src = "https://www.gstatic.com/firebasejs/6.5.0/firebase-auth.js"> </script>
<script>
// Firebase settings of your web application
var firebaseConfig = {
apiKey: "your apikey",
authDomain: "hackatonteleton.firebaseapp.com",
databaseURL: "https://name-database.firebaseio.com",
projectId: "name-projectid",
storageBucket: "name.appspot.com",
messagingSenderId: "730018138942",
Application ID: "1: 730018138942: web: eb12fac2f91fb17f"
};
// Initialize Firebase
firebase.initializeApp (firebaseConfig);
const auth = firebase.auth ();
</script>
The difference you notice is that they need:
<script src = "https://www.gstatic.com/firebasejs/6.5.0/firebase-auth.js"> </script>
and initialize the function
const auth = firebase.auth ();`enter code here`
I tried everything in this post, but nothing worked for me.
I discovered the issue with my imports and exports. This worked for me:
const auth = firebase.auth();
const database = firebase.firestore();
export { auth, database }
import { auth, database} from '#/firebase.js';
This was my mistake:
export default { auth, database }
import auth from '#/firebase.js';
My first mistake: I did a export default with two values and this doesnt work. The second mistake, if you export with curly braces, you need to import with curly braces. Otherwise you will get a "Cannot read property 'createUserWithEmailAndPassword' of undefined"
//If you have firebase version 9 you can solve it just importing firebase in this way:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
//This works in my case. For more detail follow the documentation link above:
https://firebase.google.com/docs/web/modular-upgrade
I used this import Statement & it solved the issue
import * as firebase from "firebase/app"
var auth=require("firebase/auth")
console.log(auth)
You will get to access all the methods of auth
I had the same problem with error firebase.auth is not a function since after version-8 there is a change in auth function.
I am using firebase version ^9.6.11 and below is the fix.
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
export const loginRequest = (email, password) => {
const auth = getAuth();
return signInWithEmailAndPassword(auth, email, password);
};
I hope this would help if anyone is facing same error.
My Solution: Completely Remove Node, NPM, NVM & Re-Install
This problem has happened to me a few times in the past (whenever I tried up update or install my node_modules). I literally tried everything above. It always seemed to randomly start working and I was unable to use any previously documented solution the next time the error occurred.
I think I may have had some carry-over issues since I started using Firebase in the early days when there were some weird hacks I did in macOS to get firebase to work correctly.
This solution basically completely removes any trace of node / npm / nvm from your Mac, and re-installs it to use the exact version of node that firebase runs. This uses nvm so if you have other projects that require different node versions, you can switch between node versions on the fly.
1. Delete Existing Node Modules
In your project's folder, delete any node_modules folders you have.
2. Remove Node
This is the tutorial I used to manually remove node. In the early days, I remember having to change something to install node into a different directory (due to permission issues), so I also did additional searches on my computer to remove these files and folders from other areas.
3. Remove NPM
This is the tutorial I used to make sure I removed traces of npm
4. Remove NVM
This is the tutorial I used to manually remove NVM
5. Restart
After removing everything and restarting bash (or restarting your Mac as I did for safety) - typing node, npm, and nvm into the console should simply return command not found.
6. Re-Install Node, NPM Using NVM Only
NVM allows you to install a specific version of node. Since I am using the firebase-functions node 8 runtime (beta), I installed their listed target version of node 8. (as of now, node 8.11.1). This is still in beta, firebase functions uses node 6.11.5 as of the time of this writing.
Instructions for installing node, npm using nvm
7. Update NPM Manually
NVM installed an older version of npm. This command updates NPM to its latest version.
npm install npm#latest -g
8. Install Your Modules
Restart your terminal app just in case, then return to your project folder and run the npm install command.
9. Re-Build & Re-Deploy
If you are using webpack, re-build your project. Then deploy or serve locally.
This process solved the problem for me. Hopefully it works for you and you don't have to do any hack stuff. It seems all I needed to do was some cleaning up.
I didn't need to delete my node_modules folder.
Just confirm if you've both '#firebase' and 'firebase' subfolders inside node_mudules.
If you do, change the path to 'firebase' on your require statement to
'./node_modules/firebase'
and make the next line;
require('./node_modules/firebase/firebase-auth');
For those who are using version 9
Refer this doc section
import { getAuth, GoogleAuthProvider } from "firebase/auth";
you should be using getAuthin order to get "auth" reference.
OR
try this answer if you don't want to make code changes