99

I am using Webpack with firebase and firebase-admin.

To install firebase I ran:

npm install --save firebase

I am importing firebase using:

import * as firebase from 'firebase/app'
import 'firebase/auth'

I also tried:

import * as firebase from 'firebase'

And I tried:

const firebase = require('firebase')

As suggested in web get started guide.

However, when I try to use firebase.auth() I get an error:

console.js:32 TypeError: firebase.auth is not a function

When I use the debugger to inspect firebase I see that it in fact does not have an auth function:

> firebase
 {__esModule: true, initializeApp: ƒ, app: ƒ, Promise: ƒ, …}

How can I get auth() included as a function using webpack?

6
  • 1
    Are you sure you have the latest version of Firebase installed? They make upgrades daily, so I always check to make sure my version is the latest available. Firebase Releases
    – sketchedin
    Commented Feb 3, 2018 at 1:48
  • can you confirm you have successfully initialised the firebase app? are other bits working, like the database. Commented Feb 3, 2018 at 2:18
  • If you are not sure, I wrote a guide to setting up here joshpitzalis.svbtle.com/setup and an auth specific one here joshpitzalis.svbtle.com/auth . If you're still having trouble let us know. Commented Feb 4, 2018 at 4:47
  • I had the same problem too, i did yarn install and fixed the error. Commented Jul 28, 2018 at 19:36
  • CommonJS Modules: const firebase = require('firebase/app'); require('firebase/<PACKAGE>'); ES Modules: import firebase from 'firebase/app'; import 'firebase/<PACKAGE>'; Typescript: import * as firebase from 'firebase/app'; import 'firebase/<PACKAGE>'; where the PACKAGE is the individual firebase service you want to use.
    – user10762393
    Commented Apr 28, 2020 at 5:02

28 Answers 28

91

I fixed this by deleting my node_modules directory and reinstalling everything.

Also I'm importing firebase like so:

import firebase from 'firebase'
require('firebase/auth')
5
  • 3
    Work for me as well but I did not need to reinstall node_modules. Thanks.
    – jlguenego
    Commented Apr 24, 2018 at 14:03
  • 4
    This did not work for me and seems to be an issue that occurs when you have both firebase and firebase-admin installed in the same package. Downgrading to [email protected] worked for me, with the issue appearing at [email protected]. The issue is being discussed on the firebase repo here](github.com/firebase/firebase-js-sdk/issues/752).
    – isTravis
    Commented May 4, 2018 at 22:48
  • 1
    Can confirm @isTravis's information resolved my issue. I had BOTH firebase 5.4.1 with firebase-admin 6.0.0 in my package.json. npm update firebase upgraded me to 5.5.4 and the firebase.auth() is not a function problem started appearing. The firebase-admin package wasn't even being used in my app so I npm uninstall firebase-admin and everything started working once again.
    – blaytenshi
    Commented Oct 18, 2018 at 1:32
  • I wonder if it is a version / package incompatibility problem (between firebase and firebase-admin). I reinstalled with --save, package-lock.json was updated, but now everything works.
    – jrasm91
    Commented Jun 18, 2020 at 21:37
  • Assuming you're on client, the best way I found that solves the problem is the following: import firebase from "firebase/app"; import "firebase/auth"; firebase.initializeApp({...}) export const auth = firebase.auth(); Commented Oct 23, 2020 at 14:35
47
+50

The problem wasn't with the node_modules, it was with the way that you were importing the component.

When you export a component ES6 way, you normally do export default () => { console.log('default component export'); };

default is the keyword here, when you import a component ES6 way like import firebase from 'firebase' it's grabbing the default property from the exported object.

Keeping in mind the above example, here's what you've done wrong.

Using ES6:

import * as firebase from 'firebase'

console.log(firebase.auth) // Undefined
console.log(firebase.default.auth) // Function

Using ES5:

var firebase = require('firebase')

console.log(firebase.auth) // Undefined
console.log(firebase.default.auth) // Function

Note the .default

6
  • 2
    Did you test this? When I run it I get valid entries for both auth and default.auth. My console: snag.gy/fWIUCs.jpg and my code: snag.gy/hyAoum.jpg Commented Feb 6, 2018 at 19:43
  • Didn't work when I tried. Tried on node though, not on the browser
    – Joao Lopes
    Commented Feb 7, 2018 at 23:14
  • I see. I tried in the browser. I thought the issue may have been webpack related which is why I was using the browser Commented Feb 8, 2018 at 14:47
  • 1
    "always prefer the non cargo cult answer". So if I understand: (a) re-installing packages is a red herring. (b) either require ('firebase') then firebase.default.auth OR require(firebase/auth)` then firebase.auth. +1
    – radarbob
    Commented Feb 12, 2018 at 22:24
  • @radarbob Seems to depend on the environment you're using. I tested Joao's answer and it did not work in my environment. I'm stuck with some crazy Babel Webpack Version 1 shenanigans. It was fixed for me by reinstalling the packages, and that answer has been upvoted several times so that means it probably worked for others as well. SO auto-awarded the bounty to this answer. In any case, it seems like Joao's response does help clarify some things about javascript imports in this new world, though it did not solve the issue I ran into. Commented Feb 14, 2018 at 18:21
19

I kept getting an error that said

"TypeError: firebase.auth is not a function"

I got the auth object to appear and the thing I did differently was install the modules in a different order.

The first time I installed the modules (this is when the auth object wasn't appearing):

// this seems to confuse things with the auth object when installed in this order
$ npm install firebase-admin --save
$ npm install firebase --save

I deleted the npm folder and started from scratch although this time I reversed the installation order:

// for some reason this worked and now I can access the auth object
$ npm install firebase --save
$ npm install firebase-admin --save

I didn't do anything else. I simply reversed the installation order by installing firebase first and firebase-admin second.

I hope this works for other people.

You can read more about it here

3
  • 1
    I know it’s very strange. I had a headache with this for months, did a bunch of research, nothing worked. I just randomly decided to try it and it worked. It was literally a lucky guess. 🤷🏾‍♂️ Commented Jun 21, 2018 at 17:08
  • Worked for me, thanks! Details here: github.com/firebase/firebase-js-sdk/issues/…
    – C. Bess
    Commented Oct 22, 2018 at 22:08
  • Note that firebase-admin (Which is just a firebase client with admin privileges) is not intended to be used in front-end apps like reactJS or VueJS but only in a secure server environment like stated in the docs firebase.google.com/docs/auth/admin/manage-users#create_a_user otherwise that would be a big security flaw. A solution would be using a cloud function and triggering it with an action the non-admin client could perform
    – Yidir
    Commented Feb 12, 2019 at 17:56
14

just add >

import firebase from '@firebase/app';
require('firebase/auth');

into your project

2
  • 2
    why require and not import?
    – Al Cher
    Commented Apr 1, 2019 at 14:43
  • 3
    You can use an import statement as well; ``` import Firebase from 'firebase/app'; import 'firebase/auth'; ```
    – Shahar
    Commented May 26, 2019 at 11:08
12

The main reason for this error could be due to the latest Firebase version v9.1.1, in this version the Firebase imports have been changed.

Before: version 8

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

Check docs here: https://firebase.google.com/docs/web/modular-upgrade

1
  • 1
    This is the correct solution for the latest Firebase. For similar results using 'require': const firebase = require("firebase/compat/app"); require("firebase/compat/auth"); require("firebase/compat/firestore"); Commented Oct 20, 2021 at 14:52
11

this is the import statement from official docs:

// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
// Add the Firebase products that you want to use
import "firebase/auth";
console.log(firebase.auth);

These also seem to work if you only want auth: Edit: The code below worked with Firebase 7 package but not any more with version 8. It will change again for Firebase 9. Just stick to the docs and you will be fine.

import { auth } from "firebase/app";
import "firebase/auth";
console.log(auth);

or

import { auth } from "firebase";
console.log(auth);
9

Though there are many root causes behind this issue, a simple one like this also could be the case.

I forgot to include the js files for auth and db although I use them inside the JS code.

Before the fix;

<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-app.js"></script>

After the fix;

<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-app.js"></script>

<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-auth.js"></script>

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

1
  • This is the correct answer. While ``firebase-app.js needs to be the first to be included, the other SDKs (for auth, database, etc) as required must be added separately. When using this in ES6 the specific SDK must either be imported or required separately.
    – kopos
    Commented Jul 17, 2019 at 5:36
9

You just need to use the import as following

import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";

in the above case, both auth and DB services are being used. For any other service, you need to import like that only.

8

This is because firebase-auth script is not added.

First you have to install npm files in your node modules by

npm install firebase --save
npm install firebase-admin --save

Then you have to add the script of firebase.auth after firebase-app script and make sure the version is same.

Before fix:

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

AFTER FIX YOU NEED TO ADD BOTH THE SCRIPT AND AFTER THIS ADD YOUR FIREBASE ACCOUNT SCRIPT AS FOLLOWS

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

THEN IT SHOULD WORK FINE

1
  • 1
    yes. Oddly, in the getting-started docs for the authorization package, that firebase-auth script is not prominently mentioned. It appears in a link back to setting up a firebase application, in the "Add Firebase SDKs" section: firebase.google.com/docs/web/… Commented Mar 15, 2020 at 20:56
6

With firebase v9 you can not use auth like that anymore. Instead of that you need to import auth from "firebase/auth" like:

import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";

and if you need to export auth object

const auth = getAuth();
export { auth };

if you need to use createUserWithEmailAndPassword function

createUserWithEmailAndPassword(auth, email, password)

You can check the official documentation for more

https://www.npmjs.com/package/firebase

3

When running in Node and needing both firebase and firebase-admin this works for me:

First install firebase and then firebase-admin in that order.

Then use as so:

const app = require('@firebase/app');
require('@firebase/auth');
require('@firebase/firestore');

const firebase = app.firebase

firebase.initializeApp({…})

const auth = firebase.auth()
const db = firebase.firestore()
1
  • Cannot find module '@firebase/app' If I remove the @s I get error: Cannot read properties of undefined (reading 'auth')
    – Rooster242
    Commented Jan 25, 2023 at 19:46
3

Firebase 8 introduced some breaking changes.

https://firebase.google.com/support/release-notes/js#version_800_-_october_26_2020

Now you can make it work like this if you use .default:

const firebase = require('firebase/app').default
require('firebase/auth')

if (!firebase.apps.length) {
    firebase.initializeApp(firebaseConfig)
}

const auth = firebase.auth()
2
  • 1
    I use import { default as firebase } from 'firebase/app'; in typescript
    – Eric
    Commented Mar 18, 2021 at 2:39
  • This gives me an error: Cannot read properties of undefined (reading 'apps')
    – Rooster242
    Commented Jan 25, 2023 at 19:45
3

In Firebase V9's JS SDK, thanks to Typescript, what I did is below:

import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

async login = (email: string, password: string) => {
  await signInWithEmailAndPassword(getAuth(), email, password)
}
2

I ran into this as well. My issue was the npm module @firebase was installed as well as the firebase module. When I required firebase in my JavaScript code with ‘require(“firebase”)’, webpack bundled @firebase instead for some reason.

@firebase doesn’t include auth, database etc. by default...it’s modular so you can require them separately. Consequently I received the above error when I tried calling auth().

To fix it you can remove @firebase...or just add the full path to the correct firebase when you require it like

require(‘/path/to/node_modules/firebase/firebase.js’)

1
  • 1
    This answer seems quite confused. Of course @firebase is installed (which is not a module itself; it's a "scope", with modules such as app or database under that scope). that is where most of the logic for the various firebase modules is implemented. By the way, what do you mean by your suggestion to "remove" @firebase?
    – user9315861
    Commented Jun 4, 2018 at 6:22
2

Had the same issue, I think it's because of versions troubles. I solve it by deleting node_modules and all webpack generated stuff and take versions from here.
Btw, I think it's very strange behavior, because it should work like in official documentation.

2

I had the same problem and solved it this way:

<script src = "https://www.gstatic.com/firebasejs/6.5.0/firebase-app.js"> </script>
<script src = "https://www.gstatic.com/firebasejs/6.5.0/firebase-auth.js"> </script>
<script>
// Firebase settings of your web application
var firebaseConfig = {
apiKey: "your apikey",
authDomain: "hackatonteleton.firebaseapp.com",
databaseURL: "https://name-database.firebaseio.com",
projectId: "name-projectid",
storageBucket: "name.appspot.com",
messagingSenderId: "730018138942",
Application ID: "1: 730018138942: web: eb12fac2f91fb17f"
};
// Initialize Firebase
firebase.initializeApp (firebaseConfig);
const auth = firebase.auth ();
</script>

The difference you notice is that they need:

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

and initialize the function

const auth = firebase.auth ();`enter code here`
0
2

I ran into the same problem. However I didn't have to do any deletion of any files, just correct the import statements. In my case I use Firebase version 7.7.0 in an Gatsby/React app and this is what the import looks like:

import React from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';

const config = {
  apiKey: process.env.GATSBY_FIREBASE_API_KEY,
  authDomain: process.env.GATSBY_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.GATSBY_FIREBASE_DATABASE_URL,
  projectId: process.env.GATSBY_FIREBASE_PROJECT_ID,
  storageBucket: process.env.GATSBY_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.GATSBY_FIREBASE_MESSAGING_SENDER_ID,
};

class Firebase {
  constructor() {
    firebase.initializeApp(config);
    this.auth = firebase.auth();
    this.uiConfig = {
      signinOptions: [
        firebase.auth.GoogleAuthProvider.PROVIDER_ID,
        firebase.auth.FacebookAuthProvider.PROVIDER_ID,
        firebase.auth.EmailAuthProvider.PROVIDER_ID,
      ],
    };
  }
}
export default Firebase;

const FirebaseContext = React.createContext(null);
export { FirebaseContext };

Update after request from @Mel. The context may be used using either a HOC:

export const withFirebase = Component => props => (
  <FirebaseContext.Consumer>
    {firebase => <Component {...props} firebase={firebase} />}
  </FirebaseContext.Consumer>
);

or using a hook:

import { FirebaseContext } from './firebase';
const MyComponent = () => {
  const firebase = useContext(FirebaseContext);
  // do something with firebase
};
2
  • I'm having the same problem. My config file looks like yours. Please can you show me how you managed to use in the context config. I stuck on this error and can't find a way through
    – Mel
    Commented Jan 31, 2020 at 0:34
  • @Mel I added examples how to use the context. However, in the end I switched to use gatsby-plugin-firebase, as it just works out of the box, one only have to add firebase settings. In that way I didn't have to invent the wheel again. Hope it works out for you.
    – John P
    Commented Jan 31, 2020 at 13:28
2

This may solve the issue, try this >>>

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

const firebaseConfig = {  };

  const firebaseApp = firebase.initializeApp(firebaseConfig);
  const auth = firebase.auth();
  const provider = new firebase.auth.GoogleAuthProvider();

  export { auth, provider };

most probably you forgot to put 'new' in this line --->

const provider = new firebase.auth.GoogleAuthProvider();
   

check again.

2

//If you have firebase version 9 you can solve it just importing firebase in this way:

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

//This works in my case. For more detail follow the documentation link above:

https://firebase.google.com/docs/web/modular-upgrade
1

What-up. I ran into this while working through William Candillon's Adding Firebase To React Native tutorial...

Thoughts: There is a lot to love about Firebase. But the import/export, named vs default and versioning seems to bring a lot of people a lot of unnecessary heart-ache. <-- I say that with tears streaming down my face and a hole in my heart where a love of mobile development & unhappy childhood used to exist mere hours ago.

Put simply: I had firebase.auth is not a function. Went hunting though node_modules, deleted, re-yarn'd, read blogs, tried importing as named then default, requiring separate modules a-la require('firebase/auth'); under the default import of firebase itself etc etc etc (it really shouldn't be this hard). Also, why do Google not have react documentation? It's 2018. Are people seriously still putting HTML script tags in their front end?

Current Solution => in the end I pulled all my config and firebase.initializeApp(config) into my top level app.js. I'll have to find time later to figure out why the "@firebase" module of auth can't be imported. Or why thats even there? Do i need it? Why isn't it all wrapped into the 'yarn add firebase' module?

Anyway - that'd be my advice. Get it working at top level first. Then hive-off the credentials into a separate file later. That and "Dont drink lager. It bloats-you-out and IPA is infinitely nicer."🍺🍺🍺

1

I tried everything in this post, but nothing worked for me.

I discovered the issue with my imports and exports. This worked for me:

const auth = firebase.auth();
const database = firebase.firestore();

export { auth, database } 
import { auth, database} from '@/firebase.js';

This was my mistake:

export default { auth, database }
import auth from '@/firebase.js';

My first mistake: I did a export default with two values and this doesnt work. The second mistake, if you export with curly braces, you need to import with curly braces. Otherwise you will get a "Cannot read property 'createUserWithEmailAndPassword' of undefined"

1

I used this import Statement & it solved the issue

import * as firebase from "firebase/app"
var auth=require("firebase/auth")
console.log(auth)

You will get to access all the methods of auth

1

I had the same problem with error firebase.auth is not a function since after version-8 there is a change in auth function.

I am using firebase version ^9.6.11 and below is the fix.

import { getAuth, signInWithEmailAndPassword } from "firebase/auth";
export const loginRequest = (email, password) => {
  const auth = getAuth();
  return signInWithEmailAndPassword(auth, email, password);
};

I hope this would help if anyone is facing same error.

0

My Solution: Completely Remove Node, NPM, NVM & Re-Install

This problem has happened to me a few times in the past (whenever I tried up update or install my node_modules). I literally tried everything above. It always seemed to randomly start working and I was unable to use any previously documented solution the next time the error occurred.

I think I may have had some carry-over issues since I started using Firebase in the early days when there were some weird hacks I did in macOS to get firebase to work correctly.

This solution basically completely removes any trace of node / npm / nvm from your Mac, and re-installs it to use the exact version of node that firebase runs. This uses nvm so if you have other projects that require different node versions, you can switch between node versions on the fly.

1. Delete Existing Node Modules

In your project's folder, delete any node_modules folders you have.

2. Remove Node

This is the tutorial I used to manually remove node. In the early days, I remember having to change something to install node into a different directory (due to permission issues), so I also did additional searches on my computer to remove these files and folders from other areas.

3. Remove NPM

This is the tutorial I used to make sure I removed traces of npm

4. Remove NVM

This is the tutorial I used to manually remove NVM

5. Restart

After removing everything and restarting bash (or restarting your Mac as I did for safety) - typing node, npm, and nvm into the console should simply return command not found.

6. Re-Install Node, NPM Using NVM Only

NVM allows you to install a specific version of node. Since I am using the firebase-functions node 8 runtime (beta), I installed their listed target version of node 8. (as of now, node 8.11.1). This is still in beta, firebase functions uses node 6.11.5 as of the time of this writing.

Instructions for installing node, npm using nvm

7. Update NPM Manually

NVM installed an older version of npm. This command updates NPM to its latest version.

npm install npm@latest -g

8. Install Your Modules

Restart your terminal app just in case, then return to your project folder and run the npm install command.

9. Re-Build & Re-Deploy

If you are using webpack, re-build your project. Then deploy or serve locally.

This process solved the problem for me. Hopefully it works for you and you don't have to do any hack stuff. It seems all I needed to do was some cleaning up.

0
0

I didn't need to delete my node_modules folder. Just confirm if you've both '@firebase' and 'firebase' subfolders inside node_mudules. If you do, change the path to 'firebase' on your require statement to './node_modules/firebase'

and make the next line; require('./node_modules/firebase/firebase-auth');

0

For those who are using version 9

Refer this doc section

import { getAuth, GoogleAuthProvider } from "firebase/auth";

you should be using getAuthin order to get "auth" reference.

OR

try this answer if you don't want to make code changes

0

before firebase v9

  import 'firebase/auth'

in firebase v9

  import { getAuth } from "firebase/auth";
  export const auth = getAuth(app);
1
  • 1
    Can you elaborate on what your code does and how is answers the question? don't simply post a code.
    – stramin
    Commented Feb 24, 2023 at 16:16
0

With the latest version, you can make it work like this Am using firebase version "firebase": "^10.3.0",

import * as firebase from "firebase/app";
import { getAuth, signInWithEmailAndPassword } from "firebase/auth";

const config = JSON.parse(process.env.FIREBASE_CONFIG ?? "{}");
firebase.initializeApp(config);

// @ts-ignore
const auth = getAuth();

export async function loginWithEmailAndPassword(
  email: string,
  password: string
): Promise<any> {
  try {
    const user = await signInWithEmailAndPassword(auth, email, password);
    return {
      user,
      status: true,
    };
  } catch (err) {
    return {
      error: err as Error,
      status: false,
    };
  }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.