I'm trying to make a site in React, and I have added the Firebase library using npm i firebase --save
I am then trying to call this in my app, but I am not having much joy:
import * as firebase from "firebase";
const instance = firebase.initializeApp({
apiKey: '123',
authDomain: 'https://123.firebaseapp.com/',
databaseURL: 'https://123.firebaseio.com/'
});
export default instance;
No matter what I try, it throws:
firebase.initializeApp is not a function
I've checked its in my node_modules and i've reinstalled it, but I still have no such luck.
Any suggestions?
I had a the same problem with firestore in my Vue application.
I eventually came right by doing the following in my firebase.js file:
import { firebase } from '#firebase/app'
As opposed to :
import * as firebase from 'firebase/app'
Also if you are using any specific firebase modules you need to import them individually like so:
import '#firebase/auth'
import '#firebase/firestore'
const db = firebase.firestore()
const auth = firebase.auth()
export { db, auth }
Hope this helps somebody.
This is how I solved this
import firebase from "firebase";
const firebaseConfig = {
apiKey: "Api Key",
authDomain: "Domain",
databaseURL: "URL",
projectId: "ID",
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
export default db;
Can you please try with:
var firebase = require('firebase/app');
Credits.
Been having a similar issue with firebase v4.12.1 throwing error of initializeApp not being a function. I solved it by switching to using #firebase/app 0.1.10 npm package instead.
import { firebase } from '#firebase/app';
Using it in a next.js v5.1.0 project.
been having the same problem but in VUE, in case it works i solved importing each element separately
// This import loads the firebase namespace.
import firebase from 'firebase/app';
// These imports load individual services into the firebase namespace.
import 'firebase/auth';
import 'firebase/database';
import 'firebase/firestore';
import 'firebase/storage';
Hope can help ;)
This is the new firebase SKD modular recommendation. Avoid using the
import firebase from 'firebase/app';
and try to use modular import, such as:
import {initializeApp} from "firebase/app";
const instance = {
apiKey: '123',
authDomain: 'https://123.firebaseapp.com/',
databaseURL: 'https://123.firebaseio.com/'
};
export const app = initializeApp(instance);
references
https://firebase.google.com/docs/web/learn-more#modular-version
const auth = firebase.auth()
export { db, auth }`import * as firebase from "firebase";
require("#firebase/firestore");
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export default firebase.firestore();
Related
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export default db;
Error
Module not found: Error: Package path . is not exported from package C:\Users\Sairam\Visual Code\todo-list\node_modules\firebase (see exports field in C:\Users\Sairam\Visual Code\todo-list\node_modules\firebase\package.json)
Did you mean './firebase'?
I believe the firebase had lot of updates recently, so you should update the imports this way and it worked liked a charm.
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
// Use this to initialize the firebase App
const firebaseApp = firebase.initializeApp(firebaseConfig);
// Use these for db & auth
const db = firebaseApp.firestore();
const auth = firebase.auth();
export { auth, db };
You should import like below. I see this from the firebase documentation: https://www.npmjs.com/package/firebase
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore/lite';
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
export default db;
In your Firebase config file, set up Firebase as follows:
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';
// Your web app's Firebase configuration
const config = {
//your config json file
};
firebase.initializeApp(config);
export const firestore = firebase.firestore();
export default firebase;
In the relevant .js script import Firestore and Firebase as follows:
import {firestore as db} from './firebase-config'
import firebase from './firebase-config';
If you use electron-react-boilerplate, in webpack.config.renderer.dev.dll.ts, remove firebase from the entry point. For example:
entry: {
renderer: Object.keys(dependencies || {}).filter((it) => it !== 'firebase'),
},
It is not working because you are using Firebase version-8 codes in upgraded Firebase version-9 , so if you want to solve your problem you should install Firebase version-8 by using the code below:
npm i firebase#8.2.3
I noticed that I was importing my firebase.ts config file as import db from "firebase" (absolute imports)
The issue here was that webpack was referencing the "firebase" from node_modules, rather than from my firebase.ts. And that's why it threw that error.
I fixed it by importing my firebase configs as import db from "../../firebase", and that worked
You have mistaken at const db = firebase.firestore();
It should be const db = firebaseApp.firestore();
Even after doing that you will get error of module not found. You need to import as following
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
This worked for me as I had the same issue!!
maybe i meeted the same problem when using webpack.
i solved the problem by setting webpack/configuration/resolve/#resolveconditionnames
As in v-9.8.2. Here is the docs link
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore";
import { getDatabase } from "firebase/database";
const firebaseConfig = {};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const firebaseAuth = getAuth(app);
export const fbDatabase = getDatabase(app);
export const fStore = getFirestore(app);
export const fStorage = getStorage(app);
Currently, Firebase provides two Web SDK variants. So make sure that you are using the correct version of firebase library. With version 9 firebase library was arranged independent libraries. Your syntax is using firebase version 8.
version-8 version-9
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
export default db;
Error
Module not found: Error: Package path . is not exported from package C:\Users\Sairam\Visual Code\todo-list\node_modules\firebase (see exports field in C:\Users\Sairam\Visual Code\todo-list\node_modules\firebase\package.json)
Did you mean './firebase'?
I believe the firebase had lot of updates recently, so you should update the imports this way and it worked liked a charm.
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
// Use this to initialize the firebase App
const firebaseApp = firebase.initializeApp(firebaseConfig);
// Use these for db & auth
const db = firebaseApp.firestore();
const auth = firebase.auth();
export { auth, db };
You should import like below. I see this from the firebase documentation: https://www.npmjs.com/package/firebase
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore/lite';
const firebaseConfig = {
apiKey: "AIzaSyBOK7x5N5UnjY4TDqndzH7l5tvdNIsWFRc",
authDomain: "todo-app-e3cf0.firebaseapp.com",
projectId: "todo-app-e3cf0",
storageBucket: "todo-app-e3cf0.appspot.com",
messagingSenderId: "940016886081",
appId: "1:940016886081:web:91686613f16b1b1f8001c0",
measurementId: "G-JHPC7TP12K"
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
export default db;
In your Firebase config file, set up Firebase as follows:
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';
// Your web app's Firebase configuration
const config = {
//your config json file
};
firebase.initializeApp(config);
export const firestore = firebase.firestore();
export default firebase;
In the relevant .js script import Firestore and Firebase as follows:
import {firestore as db} from './firebase-config'
import firebase from './firebase-config';
If you use electron-react-boilerplate, in webpack.config.renderer.dev.dll.ts, remove firebase from the entry point. For example:
entry: {
renderer: Object.keys(dependencies || {}).filter((it) => it !== 'firebase'),
},
It is not working because you are using Firebase version-8 codes in upgraded Firebase version-9 , so if you want to solve your problem you should install Firebase version-8 by using the code below:
npm i firebase#8.2.3
I noticed that I was importing my firebase.ts config file as import db from "firebase" (absolute imports)
The issue here was that webpack was referencing the "firebase" from node_modules, rather than from my firebase.ts. And that's why it threw that error.
I fixed it by importing my firebase configs as import db from "../../firebase", and that worked
You have mistaken at const db = firebase.firestore();
It should be const db = firebaseApp.firestore();
Even after doing that you will get error of module not found. You need to import as following
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
This worked for me as I had the same issue!!
maybe i meeted the same problem when using webpack.
i solved the problem by setting webpack/configuration/resolve/#resolveconditionnames
As in v-9.8.2. Here is the docs link
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore";
import { getDatabase } from "firebase/database";
const firebaseConfig = {};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const firebaseAuth = getAuth(app);
export const fbDatabase = getDatabase(app);
export const fStore = getFirestore(app);
export const fStorage = getStorage(app);
Currently, Firebase provides two Web SDK variants. So make sure that you are using the correct version of firebase library. With version 9 firebase library was arranged independent libraries. Your syntax is using firebase version 8.
version-8 version-9
I had this config which was working perfectly but when I added firebase-messaging it throws an error that firebase-app.js has to be loaded first
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import "firebase/database";
import "firebase/storage";
import "firebase/functions";
import "firebase/firebase-messaging"; ---> adding this line brings the error
var config = {
apiKey: "AIzaSyCrlr_yryEFERGXizzrjoPTB7biow",
authDomain: "123.firebaseapp.com",
databaseURL: "https://123.firebaseio.com",
projectId: "123",
storageBucket: "123.appspot.com",
messagingSenderId: "5025880",
appId: "1:30029661880:web:b5363d4ecddf3c32e4d64d",
measurementId: "G-DUJNZERGRQ",
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
export default firebase;
export const auth = firebase.auth();
export const db = firebase.firestore();
export const database = firebase.database();
export const storage = firebase.storage();
export const functions=firebase.functions();
export const messaging = firebase.messaging();
everything else was working before, auth, firestore, everything. I have tried adding import "firebase/firebase-app" at the top but this still does not work.
I have also upgraded the firebase sdk to the latest 7.15.4 just to be sure it's not a previous sdk bug.
What am I doing wrong
Turns out I was importing the wrong script.
It should not be import "firebase/firebase-messaging";
This is what should be imported
import "firebase/messaging";
I started a project and occurred an error when importing firebase in more than one component.
In this firebase start file:
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "fdsfsdfdsf",
authDomain: "fdsfdsfsdfdsf",
databaseURL: "sdfdsfdsf",
projectId: "dsfdsfdsf",
storageBucket: "dsfdsfdsf",
messagingSenderId: "dsfdsfsdfdsf"
}
const FbApp = firebase.initializeApp(firebaseConfig)
export default FbApp.auth()
Then in the components:
import firebase from '../lib/firebaseClient'
With a single component works well, but if I add a new component with:
import firebase from '../lib/firebaseClient'
The application fail:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
I had same issue, then I found out this:
if (!firebase.apps.length) {
firebase.initializeApp({});
}
https://github.com/zeit/next.js/issues/1999
The solution:
import firebase from 'firebase'
try {
firebase.initializeApp({
databaseURL: 'dfgdfg'
})
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
const auth = firebase.auth()
export default auth
My understanding is that the error is due to calling initializeApp() more than once for your database. Scan through your code to make sure you only call initializeApp() once. For me, this included checking any js files that might be calling the method and checking for duplicate js files in your html file.
I recently solved this error in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
On serverside something like this should work
const admin = require('firebase-admin');
const serviceAccount = require('./../../credentials/server');
// Check if firebase already been initialized
if (!admin.apps.length) {
// Initialize Firestore.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
Summarizing all good answers.
A better fix would be to load environment variables from .env.local into process.env.
//.env.local
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
Next up, we can initialize the Firebase SDK on the client-side like this.
//shared/configs/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const clientCredentials = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
if (!firebase.apps.length) {
firebase.initializeApp(clientCredentials);
}
export default firebase;
Finally, import the Firebase deps to other file.
//pages/index.js
import firebase from '../shared/configs/firebase';
So I ran into this issue because of some aspect of Next's hot reloading. I was using code like the following to ensure that I didn't call initializeApp more than once:
export let adminClient;
adminClient = adminClient || admin.initializeApp({...});
This didn't work because it seemed like the hot reloading was clearing adminClient, so I kept trying to call initializeApp, even though firebase still had the app recorded as being initialized.
To fix this, I used the following snippet:
const getAppInstance = () => {
if (admin.apps.length) {
return admin.apps[0];
} else {
return initApp();
}
}
export const adminClient = getAppInstance();
which works on a fresh server start, or when hot reloading due to code changes in development.
If you are using a new Modular SDK v9.0.1 then it might not support the "firebase" namespace.
The Implementation, I used
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
//App configure
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
if (!getApps().length) {
console.log(`...`)
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
export default app
Reference:
StackOverflow: Visit
Firebase Docs: Visit
Firebase Tutorial Setup: Visit
I started a project and occurred an error when importing firebase in more than one component.
In this firebase start file:
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "fdsfsdfdsf",
authDomain: "fdsfdsfsdfdsf",
databaseURL: "sdfdsfdsf",
projectId: "dsfdsfdsf",
storageBucket: "dsfdsfdsf",
messagingSenderId: "dsfdsfsdfdsf"
}
const FbApp = firebase.initializeApp(firebaseConfig)
export default FbApp.auth()
Then in the components:
import firebase from '../lib/firebaseClient'
With a single component works well, but if I add a new component with:
import firebase from '../lib/firebaseClient'
The application fail:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
I had same issue, then I found out this:
if (!firebase.apps.length) {
firebase.initializeApp({});
}
https://github.com/zeit/next.js/issues/1999
The solution:
import firebase from 'firebase'
try {
firebase.initializeApp({
databaseURL: 'dfgdfg'
})
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
const auth = firebase.auth()
export default auth
My understanding is that the error is due to calling initializeApp() more than once for your database. Scan through your code to make sure you only call initializeApp() once. For me, this included checking any js files that might be calling the method and checking for duplicate js files in your html file.
I recently solved this error in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
On serverside something like this should work
const admin = require('firebase-admin');
const serviceAccount = require('./../../credentials/server');
// Check if firebase already been initialized
if (!admin.apps.length) {
// Initialize Firestore.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
Summarizing all good answers.
A better fix would be to load environment variables from .env.local into process.env.
//.env.local
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
Next up, we can initialize the Firebase SDK on the client-side like this.
//shared/configs/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const clientCredentials = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
if (!firebase.apps.length) {
firebase.initializeApp(clientCredentials);
}
export default firebase;
Finally, import the Firebase deps to other file.
//pages/index.js
import firebase from '../shared/configs/firebase';
So I ran into this issue because of some aspect of Next's hot reloading. I was using code like the following to ensure that I didn't call initializeApp more than once:
export let adminClient;
adminClient = adminClient || admin.initializeApp({...});
This didn't work because it seemed like the hot reloading was clearing adminClient, so I kept trying to call initializeApp, even though firebase still had the app recorded as being initialized.
To fix this, I used the following snippet:
const getAppInstance = () => {
if (admin.apps.length) {
return admin.apps[0];
} else {
return initApp();
}
}
export const adminClient = getAppInstance();
which works on a fresh server start, or when hot reloading due to code changes in development.
If you are using a new Modular SDK v9.0.1 then it might not support the "firebase" namespace.
The Implementation, I used
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
//App configure
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
if (!getApps().length) {
console.log(`...`)
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
export default app
Reference:
StackOverflow: Visit
Firebase Docs: Visit
Firebase Tutorial Setup: Visit