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 };
There are two types of libraries available for Firebase Web SDK version 9: Modular - a new API surface designed to facilitate tree-shaking (removal of unused code) to make your web app as small and fast as possible.
For apps with a very small exposure to the Firebase Web SDK – for example, an app that makes only a simple call to the Authentication APIs – it may be practical to refactor version 8 code without using the version 9 compat libraries.
Note: FirebaseUI is not compatible with the v9 modular SDK. The v9 compatibility layer (specifically, the app-compat and auth-compat-exp packages) permits the usage of FirebaseUI alongside v9, but without the app size reduction and other benefits of the v9 SDK Has anyone solved this?
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.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With