'Uncaught TypeError: Cannot read property 'initializeApp' of undefined

I'm trying to use a few Firebase libraries in my Vue project (I installed it using npm install firebase).

I added those in main.js:

import { Firebase } from 'firebase/app'
import 'firebase/analytics'
import 'firebase/auth'
import 'firebase/messaging'

Firebase.initializeApp({
  apiKey: 'xxx',
  authDomain: 'xxx',
  databaseURL: 'xxx',
  projectId: 'xxx',
  storageBucket: 'xxx',
  messagingSenderId: 'xxx',
  appId: 'xxx',
  measurementId: 'xxx'
})

And I get:

Uncaught TypeError: Cannot read property 'initializeApp' of undefined



Solution 1:[1]

Change this:

import { Firebase } from 'firebase/app'

into this:

import * as firebase from "firebase/app";

import everything from firebase/app then do:

firebase.initializeApp({
  apiKey: 'xxx',
  authDomain: 'xxx',
  databaseURL: 'xxx',
  projectId: 'xxx',
  storageBucket: 'xxx',
  messagingSenderId: 'xxx',
  appId: 'xxx',
  measurementId: 'xxx'
})

Solution 2:[2]

For newcomers using the newest Firebase Modular API (v9) a refactoring is required.

The imports must be changed to this:

import { FirebaseApp, initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getDatabase } from "firebase/database";

const firebaseConfig = {...}

// Initialize Firebase
const app: FirebaseApp = initializeApp(firebaseConfig);

const db = getDatabase(app);

const auth = getAuth(app);

About this new refactoring style here

And more information on how Read and Write data changed here

Solution 3:[3]

Check your Firebase version in your package.json file. If it is 9+ it should be something like this:

import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
import { getAuth } from "firebase/auth";

and then:

const firebaseConfig = {
  apiKey: "...",
  authDomain: "...",
  projectId: "...",
  storageBucket: "...",
  messagingSenderId: "...",
  appId: "...",
  measurementId: "...",
};

// Initialize Firebase
const firebase = initializeApp(firebaseConfig);
const db = getFirestore(firebase);
const auth = getAuth(firebase);

Solution 4:[4]

Error that appears caused by the difference of the version you use with the installed SDK version

Simply change from like this :

import { Firebase } from 'firebase/app'
import 'firebase/analytics'
import 'firebase/auth'
import 'firebase/messaging'

to this:

   import { Firebase } from 'firebase/compat/app'
   import 'firebase/compat/analytics'
   import 'firebase/compat/auth'
   import 'firebase/compat/messaging'

For clearer info, you can read this SDK9

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Haddad
Solution 2 Dinis Rodrigues
Solution 3 Nadav
Solution 4 GigaTera