Home > Mobile >  Import * as firebase from 'firebase/app' returns undefined
Import * as firebase from 'firebase/app' returns undefined

Time:09-17

I'm trying to use firebase v9 on my Next.js project, but whenever I import it it seems to be returning undefined...

import * as firebase from 'firebase/app'

export function getFirebaseApp() {
  const clientCredentials = { ... }
  return firebase.initializeApp(clientCredentials)
}

However, when I try to run this in the browser, all I get is this error:

TypeError: Cannot read property 'initializeApp' of undefined

This happens with any variation of the import, I've tried several:

import * as firebase from 'firebase/app'
import firebase from 'firebase/app'
import { initializeApp } from 'firebase/app'

// and the same thing importing from '@firebase/app' instead, though don't think that'd ever work

I really have no idea what is going on, I don't think this is an issue from Next.js because even VSCode doesn't suggest importing anything from firebase, even though it's installed (I can see it in node_modules). I have this line in package.json:

{
  "dependencies": {
    "firebase": "^9.0.2"
  }
}

So this is a mistery really, I really have no idea what is going on. Any suggestions how I can fix this issue?

EDIT: Since I've gotten two comments suggesting this I guess I'll just put it here:

I am using the modular SDK, so I tried importing initializeApp directly, but it still did not work:

import { initializeApp } from 'firebase/app'

export function getFirebaseApp() {
  const clientCredentials = { ... }
  return initializeApp(clientCredentials)
}
TypeError: Cannot read properties of undefined (reading 'initializeApp')

CodePudding user response:

You can install the next version of firebaseui and it will work with the new SDK:

npm i -S firebaseui@next

and integrate it in your app like here.

You don't have the benefits of the new SDK if you use the compat version.

As said in the github issues both libs won't update soon so it would pay off to do this little effort and move 100% to the new SDK.

CodePudding user response:

I found the source of the issue. I was using react-firebaseui - Unfortunately, it does not support the modular version of firebase (yet). So the solution is either to use something else, or use the compat library:

import firebase from 'firebase/compat/app'
  • Related