Firebase v9 Next.js exporting getFirestore causing the error "Cannot read property 'getProvider' of undefined"

Viewed 2331
import { initializeApp, getApps, getApp } from "@firebase/firestore";
import { getFirestore } from "@firebase/firestore";

const firebaseConfig = {
  ...config
};

export default function firebaseApp() {
  if (!getApps().length) {
    firebaseApp = initializeApp(firebaseConfig);
  } else {
    firebaseApp = getApp(firebaseConfig);
  }
}

export const db = getFirestore(firebaseConfig)

Everything works fine until I try to export getFirestore as db. It works fine in CRA, but when I try to do it in Next.js I get the error "Cannot read property 'getProvider' of undefined".

I've tried everything I can think of: Used both yarn and npm, created multiple projects, imported getFirestore in another file. I am unsure what is causing this.

1 Answers

I don't understand the exact cause of the problem. I believe it has to do with some sort of mismatch of firestore instance between SSR and client or maybe await is necessary to initiate it but for now this is what worked for me:

export const db = () => getFirestore(firebaseApp)

Also, you probably want to pass the firebaseApp to getFirestore, not firebaseConfig.

Related