I got this error when trying to run my next.js app. I try lots of ways but I can't solve this. I am using firebase 9.0.1
Server Error
TypeError: Cannot read property 'apps' of undefined
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
.next\server\pages\_app.js (14:13) @ Object../firebase.js
12 | };
13 |
> 14 | const app = !firebase.apps.length
| ^
15 | ? firebase.initializeApp(firebaseConfig)
16 | : firebase.app();
Here is my firebase.js
import firebase from "firebase/app";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
const app = !firebase.apps.length
? firebase.initializeApp(firebaseConfig)
: firebase.app();
const db = app.firestore();
const auth = app.auth();
const provider = new firebase.auth.GoogleAuthProvider();
export { db, auth, provider };
Since you are using the new Modular SDK v9.0.1 which does not use firebase. namespace, you should use getApps() instead of firebase.apps.
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
const firebaseConfig = {...}
if (!getApps().length) {
//....
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
However, you don't need to check if Firebase is already initialized in this new SDK. You can learn more about the new syntax in the documentation.
Also check: Getting started with Firebase for web
if(!firebase) is giving error due to new updates. Now code look like this
import { initializeApp } from "firebase/app";
import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore";
const firebaseConfig = {
...
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
export { addDoc, db, collection };
I suggest you to re-read firebase docs, they are very updated and many video tutorials codes are not working.
links : https://firebase.google.com/docs/web/setup
https://firebase.google.com/docs/build