'firebase.firestore() is not a function when trying to initialize Cloud Firestore

When I try to initialize Firebase Cloud Firestore, I ran into the following error:

Uncaught TypeError: WEBPACK_IMPORTED_MODULE_0_firebase.firestore is not a function

I installed firebase with npm install firebase --save previously.

import * as firebase from 'firebase';
import router from '../router';

const config = {
        apiKey: "a",
        authDomain: "a",
        databaseURL: "a",
        projectId: "a",
        storageBucket: "a",
        messagingSenderId: "a"
};
if(!firebase.apps.length){
  firebase.initializeApp(config);
  let firestore = firebase.firestore();
}


Solution 1:[1]

First, make sure you have latest version of firebase:

npm install [email protected] --save

Next, add both firebase and firestore:

const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");

Initialize the firebase app:

firebase.initializeApp({
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
  projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});

// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();

source: https://firebase.google.com/docs/firestore/quickstart?authuser=0

Solution 2:[2]

import { firebase } from '@firebase/app';
import '@firebase/firestore'

If you're using authentication as well

import '@firebase/auth';

Solution 3:[3]

Hope this helps to someone who faces the same problem when deploying an Angular app to Firestore.

In Angular 8 project, I had the same error when deploying to Firestore. I fixed it by adding another module AngularFirestoreModule.

App.module.ts is like this:

...
import { AngularFireModule } from '@angular/fire';
import { AngularFirestore, AngularFirestoreModule } from '@angular/fire/firestore'; // << Note AngularFirestoreModule !!!
import { AngularFireDatabaseModule } from '@angular/fire/database';
...

imports: [
    BrowserModule,
    FormsModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFirestoreModule,
    AngularFireDatabaseModule,
...

package.json:

...
"dependencies": {
    "@angular/animations": "~8.2.2",
    "@angular/common": "~8.2.2",
    "@angular/compiler": "~8.2.2",
    "@angular/core": "~8.2.2",
    "@angular/fire": "^5.2.1",
    "@angular/forms": "~8.2.2",
    "@angular/platform-browser": "~8.2.2",
    "@angular/platform-browser-dynamic": "~8.2.2",
    "@angular/router": "~8.2.2",
    "ajv": "^6.10.2",
    "bootstrap-scss": "^4.3.1",
    "core-js": "^2.5.4",
    "firebase": "^6.4.0",
...

UPDATE: When I deployed to some other hosting provider, this did not help. For this case, I added the original firebase library and it worked.

import { firestore } from 'firebase'; 

Solution 4:[4]

If you are using the version the version 9 of firebase, then you need to use this instead:

// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';

Here is the link for the upgrade from version 8 to version 9 https://firebase.google.com/docs/web/modular-upgrade

Solution 5:[5]

You can create a separate component for initialization of firebase on you application using credentials.

firebase-context.js

import * as firebase from 'firebase'
import 'firebase/firestore';

const firebaseConfig = {
            apiKey: "XXXX",
            authDomain: "XXXXX.firebaseapp.com",
            databaseURL: "https://XXXX-app-web.firebaseio.com",
            projectId: "XXXX",
            storageBucket: "XXXX-app-web.appspot.com",
            messagingSenderId: "XXXXXX",
            appId: "1:XXX:web:XXXX",
            measurementId: "G-XXXX"
        };

export default !firebase.apps.length 
  ? firebase.initializeApp(firebaseConfig).firestore()
  : firebase.app().firestore();

In case, you need to deal with database operation you don't need to call the initialize method each time, you can use common component method which is earlier created.

import FirebaseContext from "./firebase-context";

export const getList = () => dispatch => {
    FirebaseContext.collection("Account")
        .get()
        .then(querySnapshot => {
            // success code
        }).catch(err => {
            // error code
        });
}

Solution 6:[6]

If by any chance, your code is under witchcraft, and import firebase/firestore won't work, then include it directly:

import '@firebase/firestore/dist/esm/index';

If it's not there, then:

npm install @firebase/firestore

Solution 7:[7]

I also struggled with this for a bit. what I did in the end was quite straightforward. 

for versions 9 and higher, just do the following

import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: 
  authDomain: 
  projectId: 
  storageBucket: 
  messagingSenderId: 
  appId: 
};

// Initialize Firebase

const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore;
const auth = firebaseApp.auth();


export { auth };
export default db; 

//cheers

Solution 8:[8]

The problem is not import the firestore

firebase has many features.

You need to import or import from the CDN what you want to implement from the list below.

enter image description here The official reference says to load firebase-firestore.js.

<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-firestore.js"></script>

if you want to use npm, here

npm install [email protected] --save

url is here
https://firebase.google.com/docs/firestore/quickstart?authuser=0#set_up_your_development_environment

Solution 9:[9]

I had same Error and tried to follow the official website but did not work. Then I googled error and landed in this post.

I tried:

import * as firebase from 'firebase';
import 'firebase/firestore';

However, it did not work for me but I added /firebase to the first line import * as firebase from 'firebase/firebase'; and everything is working perfectly.

It also works with require:

const firebase = require("firebase/firebase");
// Required for side-effects
require("firebase/firestore");

Solution 10:[10]

If you are updating from an earlier version of firebase and you are pulling your hair out about this issue, try const Firebase = require('firebase/firebase') instead of require('firebase/app')

Solution 11:[11]

To use firestore you need to add this link at the top of your html page.

//After initializing firebase, in your main javascript page call...
var data = firebase.firestore();
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-storage.js"></script>

Solution 12:[12]

In my case the problem was that I've accidentally added firebase-admin alongside with the firebase package in my package.json. And firebase-admin took precedence so even after adding the imports as per the accepted answer I was still getting the same error.

Removing the redundant firebase-admin from the client app fixed the problem.

As a note, firebase-admin is intended for server side to operate in admin mode, while the firebase package is a client side library.

Solution 13:[13]

Solution for Angular 8 (as of 4th January 2020):

  1. Delete package-lock.json file
  2. Run npm install
  3. import AngularFirestoreModule from @angular/fire/firestore

Just need to import AngularFirestoreModule.

// App.module.ts

import { AngularFireModule } from '@angular/fire';
import { AngularFirestore, AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFireDatabaseModule } from '@angular/fire/database';
imports: [
    AngularFireModule.initializeApp(environment.firebaseConfig),
    AngularFirestoreModule,
    AngularFireDatabaseModule
]

Solution 14:[14]

import { getFirestore } from "firebase/firestore";

Just try this and see how it goes

Solution 15:[15]

If you're like me and like everything typed on typescript (it's the purpose, by the way), you can try:

import * as firebase from "nativescript-plugin-firebase";
import { User, firestore } from "nativescript-plugin-firebase";

import * as firebaseapp from "nativescript-plugin-firebase/app";

So you can do stuff like that:

firebase.getCurrentUser().then((user: User) => { /* something */ });

const mycollection : firestore.CollectionReference = firebaseapp.firestore().collection("mycollection");

Solution 16:[16]

Removing node_modules directory together with package-lock.json and then running npm install fixed it for me.

https://github.com/angular/angularfire2/issues/1880

Solution 17:[17]

I used to have the same problem, it was a bug. I was importing firestore from firebase (it was done automatically by the IDE...) when i should imported it from the .js file where i initialized firebase app.

Solution 18:[18]

I am using the latest version of Angular 8.2.14, when I deployed to production, it cause this problem, so I add the following to app.module.ts

        imports: [
        ...,
        AngularFireModule.initializeApp(environment.firebaseConfig),
        AngularFirestoreModule,
        AngularFireDatabaseModule,
...
      ],
      providers: [AngularFirestore, AngularFirestoreModule],

Solution 19:[19]

I found a useful comment in Github by alclimb

he mentioned about firebase analytics won't work in Node.js, because it meant to be used with a browser (this is mention in the official documentation)

Solution 20:[20]

Enabling Firestore for Nativescript

During plugin installation you'll be asked whether or not you use Firestore.

In case you're upgrading and you have the firebase.nativescript.json file in your project root, edit it and add: "firestore": true. Then run rm -rf platforms && rm -rf node_modules && npm i.

init / initializeApp

By default Firestore on iOS and Android persists data locally for offline usage (web doesn't by default, and the regular Firebase DB doesn't either on any platform). If you don't like that awesome feature, you can pass persist: false to the init function.

Note that initializeApp is simply an alias for init to make the plugin compatible with the web API.

const firebase = require("nativescript-plugin-firebase/app");

firebase.initializeApp({
  persist: false
});

collection

A 'collection' is at the root of any Firestore interaction. Data is stored as a 'document' inside a collection.

 const citiesCollection = firebase.firestore().collection("cities");

Source: nativescript-plugin-firebase

Solution 21:[21]

In vanilla javascript on the client you need to include this script to make it work:

<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>

as it's not included in the default snippet Google asks you to copy paste in your website.

Source: https://firebase.google.com/docs/firestore/quickstart?authuser=0

Solution 22:[22]

For 2022 readers, please check your firebase version.

The latest version now is 9.x. It is little different from mostly YouTube guides.

You need [email protected] to follow YouTube guides.

npm uninstall firebase

npm install [email protected]

Docs: https://firebase.google.com/docs/firestore/quickstart?authuser=0#web-version-9_1

Solution 23:[23]

I think I've got it for folks using electron-webpack. Solution was from a post related to importing codemirror. https://github.com/electron-userland/electron-webpack/issues/81

This worked for me.

// package.json
{
  //...
  "electronWebpack": {
    "whiteListedModules": [
      "firebase"
    ]   
  },
  //...
}

Solution 24:[24]

In my case, the error was because I tried to import a file that used firebase.firestore() before I actually imported "firebase/firestore"

Solution 25:[25]

To use Firestore cloud functions on Node.js you should use admin.firestore() instead of admin.database(). Also you should be sure that your module firebase-admin on package.json is up to 5.4.1 or above. Looking like something like:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "dependencies": {   
    "firebase-admin": "^5.4.1",
    "firebase-functions": "^0.7.0"
  }
}