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 ?
Related
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 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
i've just tried to integrate firebase custom config at Vue. I'm newbie at this and got error like this
I already add firebase sdk to my project.
This is my main.js
Vue.config.productionTip = false
const config = {
apiKey: "######################",
authDomain: "######################",
databaseURL: "######################",
projectId: "######################",
storageBucket: "######################",
messagingSenderId: "######################",
appId: "######################",
measurementId: "######################"
};
firebase.initializeApp(config);
new Vue({
router,
vuetify,
render: h => h(App)
}).$mount('#app')
and I want to use firebase remote config on my View
<script>
import firebase from "firebase";
remoteConfig = firebase.remoteConfig();
// [START enable_dev_mode]
remoteConfig.settings = {
minimumFetchIntervalMillis: 3600000,
};
// [END enable_dev_mode]
// [START set_default_values]
remoteConfig.defaultConfig = ({
'is_auto_location': 'false',
});
// [END set_default_values]
remoteConfig.ensureInitialized()
.then(() => {
console.log('Firebase Remote Config is initialized');
setLocation();
})
.catch((err) => {
console.error('Firebase Remote Config failed to initialize', err);
});
function setLocation() {
this.isAutoLocation = remoteConfig.getString('is_auto_location');
}
</script>
please help.
Thankyou
import firebase in main.js file import * as firebase from 'firebase'
there have an awesome vuejs package for firebase call vuefire. you can use it
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();
}
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;