Firebase Remote Config on Vue - firebase

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

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

Firebase Cloud messaging (Notification)

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 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 ?

Adding FCM to vue PWA

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?

Resources