Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app) - firebase

For my Nuxt/Vue.js app I need to export various Firestore-related elements as opposed to just firebase.firestore().
However I'm getting some Firebase App named '[DEFAULT]' already exists (app/duplicate-app) error for the default export and I don't understand why:
import firebase from 'firebase/app'
import 'firebase/firestore'
const config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
const firebaseApp = firebase.initializeApp(config)
firebase.firestore().settings({ experimentalForceLongPolling: false })
const db = firebase.firestore()
const fb = firebase
export { db, fb }
export default firebaseApp
There is no duplicate that I can identify in this export default line, so what's wrong?

The way I handle it is I have a firedb file that I import as needed (throughout the App or just in Vuex). Because the file keeps getting referenced, the config keeps re-loading, which causes the same error.
The way I've dealt with it to add this line after the config definition
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
I've got an example in condesandbox at https://codesandbox.io/s/vuex-ws-2-60fzg
With your code it would be a little more difficult, since you're exporting the
firebaseAppconst. But this may work for you (not tested)
import firebase from 'firebase/app'
import 'firebase/firestore'
const config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
const firebaseApp = firebase.apps && firebase.apps.length > 0 ? firebase.apps[0] : firebase.initializeApp(config)
firebase.firestore().settings({ experimentalForceLongPolling: false })
const db = firebase.firestore()
const fb = firebase
export { db, fb }
export default firebaseApp

You can check firebase.apps to see if its loaded. If your only loading it once, then you can just check the length. If you have multiple then you could check each apps name.
// Config file
import * as firebase from "firebase";
const config = {...};
export default !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();
// Other file
import firebase from '../firebase';
...
console.log(firebase.name);
console.log(firebase.database());
If you use firestore, use :
export default !firebase.apps.length
? firebase.initializeApp(config).firestore()
: firebase.app().firestore();

You dont need to export the firebaseApp, this should be good enough
import firebase from 'firebase/app'
import 'firebase/firestore'
const config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
if (!firebase.apps.length) {
firebase.initializeApp(config)
}
firebase.firestore.settings({ experimentalForceLongPolling: false })
const db = firebase.firestore()
export { db }
export default firebase
This should avoid calling the instantiation more than once

import firebase from 'firebase/app'
import 'firebase/firestore'
const config = {
apiKey: '...',
authDomain: '...',
databaseURL: '...',
projectId: '...',
storageBucket: '...',
messagingSenderId: '...'
}
if (!firebase.apps.length) {
firebase.initializeApp(config)
}
//by commenting this i got my result
// firebase.firestore.settings({ experimentalForceLongPolling: false })
const db = firebase.firestore()
export { db }
export default firebase

this worked for me
const app = !firebase.apps.length ? firebase.initializeApp(info) : firebase.app();
export const auth = app.auth()
export default app;

this my solution in my case reactjs
if(!firebase.apps.length){
firebase.initializeApp(config);
}else{
firebase.app();
}

Related

Snack expo firebase/firestore error react native

Trying to run a react-native app (works locally!) on snack expo, but comes up with various error messages.
The first issue I think that snack expo is not ready using firebase sdk v9+, so I changed it from "firebase": "^9.16.0" to "firebase": "8.2.3" as someone suggested here.
But it means I have to change the firbase config file accordingly but I couldnt find much source to go on, so i probably made a few mistakes. This also comes up with and error and im not sure if what step I need to take next.
firebase config (^9.16.0)
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import Constants from 'expo-constants';
const firebaseConfig = {
apiKey: Constants.manifest.extra.apiKey,
authDomain: Constants.manifest.extra.authDomain,
projectId: Constants.manifest.extra.projectId,
storageBucket: Constants.manifest.extra.storageBucket,
messagingSenderId: Constants.manifest.extra.messagingSenderId,
appId: Constants.manifest.extra.appId
};
initializeApp(firebaseConfig);
export const auth = getAuth();
export const database = getFirestore();
firebase config (^8.2.3)
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import Constants from 'expo-constants';
const firebaseConfig = {
apiKey: Constants.manifest.extra.apiKey,
authDomain: Constants.manifest.extra.authDomain,
projectId: Constants.manifest.extra.projectId,
storageBucket: Constants.manifest.extra.storageBucket,
messagingSenderId: Constants.manifest.extra.messagingSenderId,
appId: Constants.manifest.extra.appId
};
initializeApp(firebaseConfig);
export const auth = getAuth();
export const database = getFirestore();
You are welcome to have a look at it on snack.expo.dev/#andrase/helfen

FirebaseError: "projectId" not provided in firebase.initializeApp (NextJS)

I'm building a web app with NextJS, NextAuth and Firebase/Firestore, and I'm getting an error:
error - [FirebaseError: "projectId" not provided in firebase.initializeApp.] {
code: 'invalid-argument',
customData: undefined,
toString: [Function (anonymous)]
This is my JS file:
import NextAuth from "next-auth/next";
import TwitterProvider from "next-auth/providers/twitter";
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { initializeApp, getApp, getApps } from "firebase/app";
import "firebase/auth";
import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore";
// import { getAnalytics } from "firebase/analytics";
// import { getStorage } from "firebase/storage";
import nextConfig from "next.config";
const firebaseConfig = {
apiKey: nextConfig.env.FIREBASE_API_KEY,
authDomain: nextConfig.env.FIREBASE_AUTH_DOMAIN,
projectId: nextConfig.env.FIREBASE_PROJECT_ID,
storageBucket: nextConfig.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: nextConfig.env.FIREBASE_MESSAGING_SENDER_ID,
appId: nextConfig.env.FIREBASE_APP_ID,
measurementId: nextConfig.env.FIREBASE_MEASUREMENT_ID,
};
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
//const analytics = getAnalytics(app);
const db = getFirestore(app);
//const storage = getStorage(app);
const dbInstance = collection(db, "bugs");
const getBugs = () => {
getDocs(dbInstance).then((data) => {
console.log(data);
});
};
export default NextAuth({
providers: [
TwitterProvider({
clientId: nextConfig.env.TWITTER_CLIENT_ID,
clientSecret: nextConfig.env.TWITTER_CLIENT_SECRET,
version: "2.0", // opt-in to Twitter OAuth 2.0
}),
],
adapter: FirestoreAdapter(db),
});
I can't find any solution on the internet.
Any idea?
In Nextjs, environment variables are only available in the Node.js environment by default, meaning they won't be exposed to the browser.
In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_
Change your firebase config as shown below and also change the firebase env variables in the .env file to use NEXT_PUBLIC_ prefix.
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_MESSAGING_SENDER_ID,
appId:process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

Vuejs Router and Firebase

I have recently decided to learn Vuejs but I couldn't figure it out if there's a way to load collections once instead of on every component.
This is what I am doing on every component before export default
The main file is where I first loaded the firebase, because of the authentication.
import firebase from '../main';
import fb from 'firebase'
let db= ''
if(firebase){
db = firebase.firestore();
}
else{
var config = {
apiKey: process.env.VUE_APP_APIKEY,
authDomain: process.env.VUE_APP_AUTHDOMAIN,
projectId: process.env.VUE_APP_PROJECTID,
storageBucket:process.env.VUE_APP_STORAGEBUCKET,
messagingSenderId: process.env.VUE_APP_MESSAGINGSENDERID,
appId: process.env.VUE_APP_APPID,
measurementId: process.env.VUE_APP_MEASUREMENTID
};
let aux_fb = !fb.apps.length ? fb.initializeApp(config) : fb.app();
db = aux_fb.firestore()
}
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router';
import fb from "firebase" ;
var config = {
apiKey: process.env.VUE_APP_APIKEY,
authDomain: process.env.VUE_APP_AUTHDOMAIN,
projectId: process.env.VUE_APP_PROJECTID,
storageBucket:process.env.VUE_APP_STORAGEBUCKET,
messagingSenderId: process.env.VUE_APP_MESSAGINGSENDERID,
appId: process.env.VUE_APP_APPID,
measurementId: process.env.VUE_APP_MEASUREMENTID
}
const firebase = !fb.apps.length ? fb.initializeApp(config) : fb.app();
export default firebase;
Vue.config.productionTip = false
let app = '';
firebase.auth().onAuthStateChanged(() => {
if (!app) {
app = new Vue({
router,
render: h => h(App)
}).$mount('#app');
}
});
Also, is it safe to use a .env ?

The timestampsInSnapshots setting now defaults to true and you no longer need to explicitly set it

When i try to connect with fire-base database in react native it generate the error
My Code:
import * as firebase from 'firebase';
import firestore from 'firebase/firestore'
const settings = {timestampsInSnapshots: true};
const config = {
apiKey: "AIzaSyAKX2eSCZ1kqBgFdiNuZ-0Q",
authDomain: "studnt-db-4.firebaseapp.com",
databaseURL: "https://studnt-db-4.firebaseio.com",
projectId: "studnt-db-4",
storageBucket: "",
messagingSenderId: "1057776",
appId: "1:1053076:web:4638390e2d"
};
firebase.initializeApp(config);
firebase.firestore().settings({settings});
export default firebase;
Change this:
firebase.firestore().settings({settings});
into this:
firebase.firestore();
You dont have to set timestampsInSnapshots: true since it is set by default

How to fix "Cannot read property 'firestore' of null" in Firestore

I will try to change the setting in the function of firestore() but doesn't work.
I read the document and they said that this future will be removed in a future release but I don't seen the solve. So I hope anyone can help me settle this problem
Operating System version: Majove 10.14.2
Library version: ^6.1.0
Firebase Product: firestore
import * as firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
// Initialize Firebase
let firebaseApp = null
if (!firebase.app.length) {
firebaseApp = firebase.initializeApp(firebaseConfig)
}
firebaseApp.firestore().settings({
ssl: false,
timestampsInSnapshots: true
})
export default firebaseApp.firestore()
See https://firebase.google.com/docs/web/setup .
Basic way to initialize firebase is this.
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import "firebase/functions";
import "firebase/storage";
import "firebase/messaging";
import "firebase/performance";
const config = {
// set your config here
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const auth = firebase.auth();
const storage = firebase.storage();
const functions = firebase.functions();
const firestore = firebase.firestore();
let messaging = null;
try {
if (firebase.messaging.isSupported()) {
messaging = firebase.messaging();
messaging.usePublicVapidKey("your publicVapidKey here");
}
} catch (e) {}
const perf = firebase.performance();
export { firebase, auth, storage, functions, firestore, messaging };
I edited your code.
import firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const firestore = firebase.firestore();
firestore.settings({
ssl: false,
timestampsInSnapshots: true
})
export default firestore;

Resources