Error with initialization of firebase while running Vue-CLI app - firebase

I'm pretty new to Vue-CLI and Firebase. I've been using Firebase for authorization and Firestore DB. I Have Encountered the following error while trying to render my application in browser:
Uncaught TypeError: __WEBPACK_IMPORTED_MODULE_3_firebase___default.a.auth is not a function
From what I've looked, it seems like there's something wrong with how I am initializing Firebase, but I couldn't find the problem.
Here is my main.js file:
import Vue from 'vue'
import App from './App'
import router from './router'
import firebase from 'firebase'
import 'firebase/firestore'
Vue.config.productionTip = false
let app
let fireBaseConfig = {
apiKey: ***,
authDomain: ***,
databaseURL: ***,
projectId: ***,
storageBucket: ***,
messagingSenderId: ***
};
firebase.initializeApp(fireBaseConfig)
firebase.auth().onAuthStateChanged(function(user){
if(!app){
/* eslint-disable no-new */
app = new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
}
});
const firestore = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
export { firestore }

Related

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,
};

I can't add data from my vue.js page to firestore database

I am new to vue.js and firebase
I want to add a collection to my firebase/firestore database from my Vue page
Here's my code:
<script>
import db from '#/fb'
export default {
methods: {
addTask(){
const project = {
title: 'some title',
content:'some content',
due:'01/01/2021',
person: 'someone',
status:'ongoiing'
}
db.collection('projects').add(project).then(() => {
console.log('added to database')
})
...
and this is my firestore project configuration that I put in the 'fb.js' file on the 'src' folder:
//import firebase from 'firebase'
import firebase from 'firebase/app'
import 'firebase/firestore'
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "XXXXXX",
authDomain: "XXXX.firebaseapp.com",
projectId: "XXXXX",
storageBucket: "XXXXX.appspot.com",
messagingSenderId: "XXXXXXXX",
appId: "1:XXX:web:XXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.firestore();
db.settings({timestampsInSnapshots:true})
export default db;
My problem is when I click on the add button, nothing happens
Thanks a lot for the help

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 ?

FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

Hey I am pulling my hair out on this one - I have read several posts here but keep getting this error here is my code for init.js
import firebase from "firebase/app"
var config = {
apiKey: "AIzaSyAF2VbjdWbQdsdsdk79nINQV5wdsdBn-uMy844gY7s",
authDomain: "lcarchivewebsite.firebaseapp.com",
databaseURL: "https://lcarchivewebsite.firebaseio.com",
projectId: "lcarchivewebsite",
storageBucket: "lcarchivewebsite.appspot.com",
messagingSenderId: "71812947145517",
appId: "1:718129478445517:web:0284d6bsdsdbb57384c87800c4"
};
firebase.initializeApp(config);
export const firestore = firebase.firestore()
export const db = firebase.database()
export const auth = firebase.auth()
export const storage = firebase.storage()
my component is here:
<template>
<h2>hello</h2>
</template>
<script>
import storage from 'firebase'
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
created(){
var storageRef = storage.storage().ref()
var listRef = storageRef.child('2020')
listRef.listAll().then((response) => {console.log(response)})
}
}
</script>
i have installed firebase with npm install --save
here is package.json
"dependencies": {
"firebase": "^7.17.1",
"materialize-css": "^1.0.0",
"vue": "^2.5.2",
"vue-router": "^3.0.1",
"webpack-cli": "^3.3.12"
},
Couple of problems here, the first being that you are importing from the firebase lib in node_modules where you should be importing the storage you exported from your init.js script.
Fix this with
import { storage } from '#/path/to/init.js' // "#" refers to your "src" directory
// snip
var storageRef = storage.ref()
The other problem is that in order to use Firebase features like storage, you need to import those libs. So in init.js...
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/database'
import 'firebase/firestore'
import 'firebase/storage'

Using firebase in vuejs2 app via vue-cli(webpack)

I am new to using vue-cli a webpack template
I want to use firebase as my database for the vueapp
i have done this to import Firebase into my app
main.js
//imported rest all required packages just dint mention here
import * as firebase from 'firebase'
let config = {
apiKey: " - XXXXXXXXCXCC",
authDomain: "XXXXXXXXX",
databaseURL: "XXXXXCCCX",
storageBucket: "XXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXX"
};
firebase.initializeApp(config);
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
Now in my signup.vue file i have to import the following again
import * as firebase from 'firebase'
In order to use the following in my methods
firebase.auth().createUserWithEmailAndPassword(uEmail, uPassword).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
My question is do i have to import
import * as firebase from 'firebase'
everywhere (i.e in alll vue components script tags to use firebase related methods like
firebase.auth()
firebase.database()
firebase.storage()
or can i import it at one central place and use firebase.method() in any vue component file when needed
You could attach the firebase to the Vue.prototype:
import * as firebase from 'firebase'
let config = {
//
}
Vue.prototype.$firebase = firebase.initializeApp(config)
new Vue({
//
})
Then, use it to the components like this:
this.$firebase.database()
If you want to import it just once, you can simply do in your main.js:
import * as firebase from 'firebase'
window.firebase = firebase
window object is global for webpage and it's normal practice to use it this way.

Resources