I'm writing a web app with Nuxt.js and Firebase. In which file do I need to initialize the Firebase? In other words, where to put this code snippet?
var config = {
apiKey: "xxxxxxxxxx",
authDomain: "xxxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxx.firebaseio.com",
projectId: "xxxxxxxxx",
storageBucket: "xxxxxxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxxx"
};
firebase.initializeApp(config);
Create file firebase.js in folder plugins.
import firebase from 'firebase'
import 'firebase/firestore' //if use firestore
if (!firebase.apps.length) {
firebase.initializeApp({
apiKey: "xxx",
authDomain: "xxx",
databaseURL: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx"
})
}
firebase.firestore().settings({ timestampsInSnapshots: true })
const db = firebase.firestore()
const storage = firebase.storage() //if use storage
export { storage, db }
In component:
import { db } from '~/plugins/firebase.js'
data() {
return {
users: []
}
},
mounted() {
db.collection("users").get().then((querySnapshot) => {
this.users = querySnapshot.docs.map(doc =>
Object.assign({ id: doc.id }, doc.data())
)
})
}
Related
I'm new here. Been having issues with working with the firebase cloud messaging. Tried sending notification throught the the notification composer but it not promting any notification at my side. N:B I have no knowledge of backend technologies, so only implemented it in the front-end.
This is my code
// For the App.js folder
import { initializeApp } from "firebase/app";
import { getToken, getMessaging, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
Notification.requestPermission().then((permission) => {
if(permission === 'granted'){
console.log('permission granted')
}
})
.catch((err) => {
console.log('permission denied:', err)
})
getToken(messaging, {vapidKey: 'BMRthb-93vz-iQl0XQA8AsKbzMyLq-f2JCB00B2rMb35Z_1iVdWX8CquQ820-z6vyMmdDB0W46FIIS3R5IhTbXY'}).then((token) => {
console.log('my token is', token);
});
onMessage(messaging, (payload) => {
console.log(payload.notification);
new Notification(payload.notification.title, {
body:payload.notification.body
})
})
For the Service worker folder
import { getMessaging, onBackgroundMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js");
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('received background messages:', payload)
const notificationTitle= payload.notification.notificationTitle
const notificationBody = {
body: payload.notification.body,
}
self.registration.showNotification(notificationTitle, notificationBody);
})
i would apprecitate if someone can come through for me. thanks[image 1(app.jsimage2 (app.js)](https://i.stack.imgur.com/tMoq2.png)
Tried evrything, but to no avail. I want to be able to send notifications to user via the notificTION COMPOSER
I'm using Expo SDK for my ios app, when I try to write data in the firebase database but I'm getting the error. Error: FIREBASE FATAL ERROR: Cannot parse Firebase URL. Please use https://.firebaseio.com*
My firebase config file is
const firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxxxxxxxxxx.europe-west1.firebasedatabase.app",
projectId: "xxxxx",
storageBucket: "xxxxxxx.appspot.com",
messagingSenderId: "xxxxxxxxx",
appId: "xxxxxxxxxx",
measurementId: "xxxxxx"
};
my function that stores the data is
signUp = () => {
const user = firebase.auth().currentUser;
let userid = user.uid;
firebase
.database()
.ref(`users/${userid}`)
.set({
firstname: this.state.firstname,
lastname: this.state.lastname,
password: this.state.password,
email: this.state.email,
dob: this.state.dob,
postcode: this.state.postcode,
})
.then(() => {
alert("user created");
})
.catch((err) => {
alert("error");
});
};
My database rules are set to true for reading and write.
I have tried the following database URL but none of them work.
const firebaseConfig = {
databaseURL: "https://xxxxxxxxxxxxxx.europe-west1.firebaseio.com",
};
const firebaseConfig = {
databaseURL: "https://xxxxxxxxxxxxxx.firebaseio.com",
};
Looking for help, please
firebaser here
Somehow Expo seems to pin you on Firebase SDK version 7.9, which was released in February 2020. This predates the addition of the firebasedatabase.app URLs, which happened in May 2020, and was released in version 7.15.4 of the JavaScript SDK, as far as I can see.
The problem disappears when I upgrade the SDK dependency to 7.14.5, despite the Expo Snack editor showing an error when I do:
{
"dependencies": {
"react-native-paper": "3.6.0",
"expo-constants": "~9.3.1",
"firebase": "7.14.5"
}
}
My recommendation would be to upgrade to the latest versions of the SDK, as shown in the configuration snippets in the Firebase console and documentation.
Upgrading Firebase package to the latest version fixes the issue
"firebase": "^8.2.3"
Did you initialize the config? Something like this.
import firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/database';
import 'firebase/auth';
import 'firebase/storage';
import 'firebase/functions';
interface ConfigProps {
apiKey: string;
authDomain: string;
databaseURL: string;
projectId: string;
storageBucket: string;
messagingSenderId: string;
appId: string;
}
const config: ConfigProps = {
apiKey: '******************',
authDomain: '******************',
databaseURL: '******************',
projectId: '******************,
storageBucket: '******************',
messagingSenderId: '******************',
appId: '******************',
};
firebase.initializeApp(config);
firebase.firestore();
export default firebase;
I am trying to add Firebase Massaging to my VueJS PWA app, but I am getting the following error:
# ./src/main.js 6:0-28 28:13-16 # multi
(webpack)-dev-server/client?http://192.168.1.7:8080/sockjs-node
(webpack)/hot/dev-server.js ./src/main.js
manifest.json in the Public folder looks like :
"start_url": ".",
"display": "standalone",
"background_color": "#000000",
"theme_color": "#210499",
"gcm_sender_id": "103953800507"
firebase-messaging-sw.js in the public folder looks like :
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
var config = {
messagingSenderId: "452219633362"
};
firebase.initializeApp(config);
let messaging = firebase.messaging();
App.vue file Looks like :
created() {
var config = {
apiKey: "My apiKey",
authDomain: "My firebase domain",
databaseURL: "database URL",
projectId: "Project ID",
storageBucket: "storage Bucket",
messagingSenderId: "Sender id "
};
firebase.initializeApp(config);
let messaging = firebase.messaging();
messaging
.requestPermission()
.then(() => firebase.messaging().getToken())
.then(token => {
console.log(token); // Receiver Token to use in the notification
})
.catch(function(err) {
console.log("Unable to get permission to notify.", err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
}
main.js looks like :
import Vue from "vue";
import App from "./App.vue";
import firebase from "firebase";
import "../public/firebase-messaging-sw"
Vue.config.productionTip = false;
var config = {
apiKey: "My apiKey",
authDomain: "My firebase domain",
databaseURL: "database URL",
projectId: "Project ID",
storageBucket: "storage Bucket",
messagingSenderId: "Sender id "
};
firebase.initializeApp(config);
Vue.prototype.$messaging = firebase.messaging()
navigator.serviceWorker.register('/firebase-messaging-sw.js')
.then((registration) => {
Vue.prototype.$messaging.useServiceWorker(registration)
}).catch(err => {
console.log(err)
})
new Vue({
render: h => h(App)
}).$mount("#app");
I cannot point out what I did wrong. I did use Vue-Cli version 3. Can someone help me with this error?
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 have a firebase config file like this:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const firebaseApp = firebaseApp;
I am trying to authenticate a user but keep getting firebaseApp.auth() is not a function.
let me = db.collection('staff').where('email', '==', this.current_user.email)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
this.fbUser = doc.id;
let email = doc.data().email;
let pw = doc.data().key;
firebaseApp.auth().onAuthStateChanged(user => {
if (user) {
//console.log('Already authenticated.');
} else {
firebaseApp.auth().signInWithEmailAndPassword(email, pw)
.then(liu => {
//console.log('Logged in', liu.uid);
let uid = liu.uid;
this.$localStorage.set('fbId',this.fbUser, 0);
this.$localStorage.set('fbAuthId', uid, 0);
me.update({
is_active: true
});
});
} // end if
});
});
Don't I have to configure the app? There's no auth functionality in #firebase.
Any help is appreciated.
You should add the auth Firebase service in your initialization, as follows:
import { firebase } from "#firebase/app";
import "#firebase/firestore";
import "#firebase/auth"; // <- NEW
const firebaseApp = firebase.initializeApp({
apiKey: "myKey",
authDomain: "myDomain",
databaseURL: "myURL",
projectId: "myProject",
storageBucket: "myBucket",
messagingSenderId: "999999999"
});
export const db = firebaseApp.firestore();
export const auth = firebaseApp.auth(); // <- NEW
export const firebaseApp = firebaseApp;
Then, in your component, you do:
auth.onAuthStateChanged(user => {})
and
auth.signInWithEmailAndPassword(email, pw)