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

JavascriptFirebaseGoogle Cloud-Firestore

Javascript Problem Overview


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();
}

Javascript Solutions


Solution 1 - Javascript

I fixed it by importing multiple libraries: firebase and firebase/firestore. That's because the firebase core library does not include the firestore library.

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

Solution 2 - Javascript

First, make sure you have latest version of firebase:

npm install firebase@4.12.0 --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 3 - Javascript

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

If you're using authentication as well

import '@firebase/auth';

Solution 4 - Javascript

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 5 - Javascript

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 - Javascript

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 7 - Javascript

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 8 - Javascript

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 firebase@7.19.0 --save

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

Solution 9 - Javascript

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 10 - Javascript

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 11 - Javascript

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 12 - Javascript

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 13 - Javascript

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 14 - Javascript

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 15 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

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 - Javascript

import { getFirestore } from "firebase/firestore";

Just try this and see how it goes

Solution 24 - Javascript

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 25 - Javascript

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

Solution 26 - Javascript

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"
  }
}

Solution 27 - Javascript

simply the answer is just to link these script in your html file and check that the issue is resolved

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

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

gives upvote if it is helpful for fixing your problem

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEyk RehbeinView Question on Stackoverflow
Solution 1 - JavascriptEyk RehbeinView Answer on Stackoverflow
Solution 2 - JavascriptRamsy de VosView Answer on Stackoverflow
Solution 3 - JavascriptTim ArneyView Answer on Stackoverflow
Solution 4 - JavascriptAtilla BaspinarView Answer on Stackoverflow
Solution 5 - JavascriptankitkanojiaView Answer on Stackoverflow
Solution 6 - JavascriptAshfaq nisarView Answer on Stackoverflow
Solution 7 - JavascriptJose AView Answer on Stackoverflow
Solution 8 - JavascriptHideyasu.TView Answer on Stackoverflow
Solution 9 - Javascriptbos_devView Answer on Stackoverflow
Solution 10 - JavascriptYousaf AzabiView Answer on Stackoverflow
Solution 11 - JavascriptbytecodeView Answer on Stackoverflow
Solution 12 - JavascriptAlex_MinasyanView Answer on Stackoverflow
Solution 13 - Javascriptvir usView Answer on Stackoverflow
Solution 14 - Javascriptuser12602844View Answer on Stackoverflow
Solution 15 - JavascriptBruno LeitãoView Answer on Stackoverflow
Solution 16 - JavascriptAustris CirulnieksView Answer on Stackoverflow
Solution 17 - JavascriptJavier AlejandroView Answer on Stackoverflow
Solution 18 - JavascriptLesterView Answer on Stackoverflow
Solution 19 - JavascriptMondayView Answer on Stackoverflow
Solution 20 - JavascriptalignncView Answer on Stackoverflow
Solution 21 - JavascriptelooneView Answer on Stackoverflow
Solution 22 - Javascriptuser16806454View Answer on Stackoverflow
Solution 23 - JavascriptChimaobi EzeobidiView Answer on Stackoverflow
Solution 24 - JavascriptbtdView Answer on Stackoverflow
Solution 25 - JavascriptCyril TroitskyView Answer on Stackoverflow
Solution 26 - JavascriptFrancisco Durdin GarciaView Answer on Stackoverflow
Solution 27 - JavascriptShubham TomarView Answer on Stackoverflow