Setting up Firebase and Vue: Best practices for initializing Firebase and Vuefire

I am encountering an issue while setting up Vuefire and Firebase in my application. The error that I see in the console is:

FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
    at initializeApp (webpack-internal:///./node_modules/@firebase/app/dist/index.cjs.js:377:33)
    at Object.firebase.initializeApp (webpack-internal:///./node_modules/@firebase/app/dist/index.cjs.js:667:26)
    at eval (webpack-internal:///./src/db.js:28:70)
    at Module../src/db.js (http://localhost:8080/js/about.js:323:1)
    at __webpack_require__ (http://localhost:8080/js/app.js:854:30)
    at fn (http://localhost:8080/js/app.js:151:20)
    at eval (webpack-internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/Photos.vue?vue&type=script&lang=js&:2:61)
    at Module../node_modules/cache-loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/Photos.vue?vue&type=script&lang=js& (http://localhost:8080/js/about.js:167:1)
    at __webpack_require__ (http://localhost:8080/js/app.js:854:30)
    at fn (http://localhost:8080/js/app.js:151:20)

Below is the snippet from my db.js file:

import * as firebase from 'firebase/app'
// Add the Firebase products that you want to use
import 'firebase/auth'
import 'firebase/firestore'

const firebaseConfig = {
  apiKey: 'xxx',
  authDomain: 'xxx',
  databaseURL: 'xxx',
  projectId: 'xxx',
  storageBucket: 'xxx',
  messagingSenderId: 'xxx',
  appId: 'xxx'
}

// Get a Firestore instance
export const db = firebase.initializeApp({ projectId: firebaseConfig.projectId }).firestore()
// Use Auth module
export const auth = firebase.initializeApp(firebaseConfig).auth()

// Export types that exist in Firestore
// Assuming we might want to use these features later
const { Timestamp, GeoPoint } = firebase.firestore
export { Timestamp, GeoPoint }

Thank you for any assistance!

Answer №1

Finally got it to work! The key was a simple adjustment. I initially thought I needed to initialize firebase/auth, but all I actually had to do was import the firebase module in the login component.

Login.vue

<script>
import firebase from 'firebase/app'
export default {
  name: 'Login',
  data() {
...snip...
  methods: {
    login() {
      const info = {
        email: this.formData.email,
        password: this.formData.password
      }
      firebase
        .auth()
        .signInWithEmailAndPassword(info.email, info.password)
        .then(
          () => {
            this.$router.push('photos')
          },
          error => {
            this.error = error.message
          }
        )
    }
  }

Photos.vue

<script>
import { db } from '@/db'
export default {
  props: ['user'],
  name: 'Photos',
  data() {
    return {
      photos: []
    }
  },
  firestore: {
    photos: db.collection('photos').orderBy('title')
  },
  methods: {
    // submitHandler(data) {
    //   // alert(`Thank you, ${data.firstname}`);
    //   db.collection("users")
    //     .add({
    //       firstname: data.firstname
    //     })
    //     .then(docRef => {
    //       console.log("Doc Id: ", docRef.id);
    //     })
    //     .catch(error => {
    //       console.error("error: ", error);
    //     });
    // }
    //     addName() {
    //   db.collection("users")
    //     .add({
    //       first: "Ada",
    //       last: "Lovelace",
    //       born: 1815
    //     })
    //     .then(function(docRef) {
    //       console.log("Document written with ID: ", docRef.id);
    //     })
    //     .catch(function(error) {
    //       console.error("Error adding document: ", error);
    //     });
    // }
  }
}
</script>

db.js:

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

const firebaseConfig = {
 ..config here..
}

// firebase.initializeApp(firebaseConfig)

// Get a Firestore instance
export const db = firebase.initializeApp(firebaseConfig).firestore()

//guess I dont' need to do this here
// export const auth = firebase.initializeApp(firebaseConfig).auth()

// Export types that exists in Firestore
// Assuming might want to use these features later
const { Timestamp, GeoPoint } = firebase.firestore
export { Timestamp, GeoPoint }

For vuefire, my main.js looks like so:

import Vue from "vue"

import App from "./App.vue"
import router from "./router"
import { firestorePlugin } from "vuefire"
import "bootstrap/dist/css/bootstrap.min.css"

Vue.config.productionTip = false
Vue.use(firestorePlugin)

new Vue({
    router,
    render: (h) => h(App)
}).$mount("#app")

Not sure if this is the most efficient way to reduce bundle size, so if anyone has suggestions, feel free to share. But for now, grateful for the assistance!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript Function to Redirect Page After a Delay of X Seconds

I'm trying to implement a redirect to a specific URL after displaying an error message for 5 seconds. Initially, I used JavaScript like this: document.ready(window.setTimeout(location.href = "https://www.google.co.in",5000)); However, the redirectio ...

Guide to building an HTML table using an array of objects

Is there a way to dynamically create a table from an array of objects? Here's an example array: let data = [{name: 'Player1',score:10}, {name: 'Player2',score: 7}, {name: 'Player3',score:3}] The desired HTML output shou ...

Retrieve the observable value and store it in a variable within my Angular 13 component

Incorporating Angular 13, my service contains the following observable: private _user = new BehaviorSubject<ApplicationUser | null>(null); user$ = this._user.asObservable(); The ApplicationUser model is defined as: export interface ...

Unclear result encountered within promise sequence

I built a simple employee profile generator app, and everything seems to be working fine until the promise for generatePage(employeeData) is not passing the data correctly. Can anyone provide insight into why this might be happening? I have also attached a ...

Combining Vue-leaflet with Vuetify

Having an issue with vue-leaflet and vuetyfy. I have a simple template that displays different layouts depending on mobile or not. When the app detects mobile, I want to make a 2-row layout - the first row for the map and the second for the input form. How ...

Exploring the world of asynchronous operations with React Hooks

Hello, I am a beginner when it comes to React and JavaScript. I could really use some assistance with two hooks that I have created: useSaveStorage and useGetStorage. The issue I am facing is that my app is supposed to receive data and save it into AsyncS ...

Retrieve all records from a table using Prisma client

I need to retrieve all data from a table using Prisma. How can I achieve this? (SELECT * FROM application) const applications = prisma.application.findMany({ // Retrieves all fields for the user include: { posts: { ...

What is the best way to convert JSON data into a string array and showcase the results?

Recently, I've been exploring the fetch API to retrieve some data. After successfully fetching the data and displaying the response using console log, I now face a challenge in utilizing this information. The API provides me with "result", "id", and " ...

Using regular expressions to eliminate select special characters from text

What is the best way to eliminate certain special characters from a string using regex in JavaScript? apostrophes ' quotation marks " ampersand symbol & registered symbol ® trademark symbol ™ ...

Switching button presses

http://jsfiddle.net/qVfy7/ HTML <div id='button'></div> <div id="mydiv">ko</div> JS $('#button').click(function () { $('#mydiv').text('ok'); }); CSS #button{ width:100px; he ...

Retrieve the dimensions of an image once rendering is complete, using Angular

I'm currently working on obtaining the rendered size of an image within a component. By utilizing the (load) event, I can capture the size of the image as it appears at that particular moment (pic1), as well as its "final" size after the page has fini ...

Discovering an element within a shadow root using Selenium in conjunction with Java

Is there a way to retrieve the "Solve the challenge" button from within the shadow-root (closed) element? Here is what I've attempted so far: driver.findElement(By.xpath("//[@id=\"solver-button\"]")).click(); Unfortunately, the button canno ...

Encountering an incorrect number of parameters for "undefined" during the deployment of a smart contract

I am facing an issue while attempting to deploy my first Voting contract on the testRPC. The error seems to arise from the arguments parameter in the code snippet below. When I tried passing an empty array, it gave an error stating "Got 0 expected 1!". Si ...

Utilizing the invoke() method within the each() function in Cypress to access the href attribute

I recently started using Cypress and I'm attempting to retrieve the href attribute for each div tag within a group by utilizing invoke(), however, it is resulting in an error. Could anyone provide guidance on the correct way to achieve this? cy.get(&a ...

Is it possible to create a collapse and expand animation that does not involve transitioning the `height

After extensively researching, I have come across numerous articles advocating for the use of transform and opacity for achieving smooth CSS transitions. An example can be found here: The prevailing notion always revolves around: ...the optimization ...

What could be the reason for the issue `injection "store" not found` showing up when attempting to call `this.store.commit()`?

I am currently working on storing values with VueX, specifically using Vuex 4.0 instead of the older version 3.0. While attempting to commit a value, I encountered an issue as follows: ... this.$store.commit("changerusername", u) ... To addres ...

The compatibility between Laravel's @vite('resources/js/app.js') and the froala editor plugin seems to be causing issues

I have incorporated a Vue.js based commenting system and inbox messages system in my Laravel website. Additionally, I am utilizing a wysiwyg editor (Froala Editor) in my forms for uploading projects. The issue I am facing is that the Froala Editor does no ...

Highlighted Answer: Choosing between two options in the quiz

I am currently developing an employability quiz for my university project. Each question offers a choice between Yes and No answers. If the user selects the Yes answer, it will be highlighted in green and display the correct answer below. However, if the ...

Step-by-step guide on making a duplicate of a Search bar

I have a search field in my application that I want to duplicate. The goal is to create two identical search fields, one on the left side of the page and another on the right side. How can I achieve this using JavaScript? Here is my JavaScript code: doc ...

The command "npm run build" is failing and encountering errors within the webpack project

Today, when I ran npm run build in the terminal, my project stopped running and displayed 90 errors and 13 warnings. It was working fine yesterday, so I'm not sure what the issue could be. The only change I made was to a line of JavaScript code that i ...