Firebase config file dynamic import at Vue - firebase

firebaseInit.js
import firebase from 'firebase/app';
const FirebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
};
firebase.initializeApp(FirebaseConfig);
export default firebase;
what did i try;
var data = async function getConfig() {
var x= await fetch('/someurl')
.then(function(res) {
return res.json();
})
.catch(function(err) {
return console.log(err);
});
return x;
};
firebase.initializeApp(getConfig());
export default firebase;
i can get external config file but it is not exporting..................................

Export a promise-returning function...
// firebaseInit.js
import firebase from "firebase/app";
export default function() {
return fetch('/someurl').then(res => {
firebase.initializeApp(res.json());
return firebase
}).catch(err => {
console.log(err);
throw err;
});
};
Await it in the importing module...
import firebasePromise from 'firebaseInit.js'
let firebase;
async someFunction() {
firebase = firebase || await firebasePromise();
// use firebase
}

Related

Service messaging is not available

I want to integrate FCM with nextjs project.
This error is occurring whenever I save the firebase.js config file. I'm not being able to use Firebase Cloud Messaging in Firebase V9.
I use firebase 9.10.0
my firebase.js config
import { initializeApp } from 'firebase/app';
import { getToken, getMessaging, onMessage } from 'firebase/messaging';
const firebaseConfig = {
apiKey: "*************",
authDomain: "********************",
projectId: "******************",
storageBucket: "*****************",
messagingSenderId: "*************",
appId: "**********************"
};
console.log('*** Environment ***', process.env.REACT_APP_ENV)
console.log('*** Firebase Config ***', firebaseConfig)
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
export const getOrRegisterServiceWorker = () => {
if ('serviceWorker' in navigator) {
return window.navigator.serviceWorker
.getRegistration('/firebase-push-notification-scope')
.then((serviceWorker) => {
if (serviceWorker) return serviceWorker;
return window.navigator.serviceWorker.register('/firebase-messaging-sw.js', {
scope: '/firebase-push-notification-scope',
});
});
}
throw new Error('The browser doesn`t support service worker.');
};
export const getFirebaseToken = () =>
getOrRegisterServiceWorker()
.then((serviceWorkerRegistration) =>
getToken(messaging, { vapidKey: "***********", serviceWorkerRegistration }));
export const onForegroundMessage = () =>
new Promise((resolve) => onMessage(messaging, (payload) => resolve(payload)));
Ather searing a lot I found solutions:
I change the code of my firebase.js file to the below code
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getMessaging, getToken } from "firebase/messaging";
import localforage from "localforage";
const firebaseConfig = {
apiKey: "**********************",
authDomain: "*******************",
projectId: "******************",
storageBucket: "****************",
messagingSenderId: "****************",
appId: "**************"
};
// Initialize Firebase
const firebaseCloudMessaging = {
init: async () => {
initializeApp(firebaseConfig);
try {
const messaging = getMessaging();
const tokenInLocalForage = await localStorage.getItem("fcm_token");
// Return the token if it is alredy in our local storage
if (tokenInLocalForage !== null) {
return tokenInLocalForage;
}
// Request the push notification permission from browser
const status = await Notification.requestPermission();
if (status && status === "granted") {
// Get new token from Firebase
const fcm_token = await getToken(messaging, {
vapidKey:
"********************",
});
console.log("token in fcm_token", fcm_token);
// Set token in our local storage
if (fcm_token) {
localforage.setItem("fcm_token", fcm_token);
return fcm_token;
}
}
} catch (error) {
console.error(error);
return null;
}
},
};
export { firebaseCloudMessaging };

TypeError: _app.default.firestore is not a function. (In '_app.default.firestore()', '_app.default.firestore' is undefined)

The error occurs right when I build the project, it doesn't return any information about where the error is or something, help me please!
My firebase config:
import firebase from 'firebase/compat/app';
require('firebase/firestore')
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "-",
authDomain: "-",
projectId: "-",
storageBucket: "-",
messagingSenderId: "-",
appId: "-"
};
// Initialize Firebase
let app;
if(firebase.apps.length === 0){
app = firebase.initializeApp(firebaseConfig);
}else{
app = firebase.app()
}
const db = firebase.firestore();
export { db };
Below I leave my fire.js finds all the logic for the file where the post is sent with image text.
Note: firebase collection is configured correctly, with name and my fields.
import firebaseConfig from './firestore';
import firebase from "firebase/compat/app";
class Fire {
constructor() {
firebase.initializeApp(firebaseConfig);
}
addPost = async ({ text, localUri }) => {
const remoteUri = await this.uploadPhotoAsync(localUri);
return new Promise((res, rej) => {
this.firestore
.collection("posts")
.add({
text,
uid: this.uid,
timestamp: this.timestamp,
image: remoteUri,
})
.then((ref) => {
res(ref);
})
.catch((error) => {
rej(error);
});
});
};
uploadPhotoAsync = async (uri) => {
const path = `photos/${this.uid}/${Date.now()}.jpg`;
return new Promise(async (res, rej) => {
const response = await fetch(uri);
const file = await response.blob();
let upload = firebase.storage().ref(path).put(file);
upload.on(
"state_changed",
(snapshot) => {},
(err) => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
}
);
});
};
get firestore() {
return firebase.firestore();
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;

How do I configure SvelteKit to use Firebase Auth?

I have it working with Firebase 8, but I can't seem to get Firebase 9 working...
Here is my firebaseConfig.js file:
import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: 'AIzaSyCAAngD7340_noXs7eesCfE9Y3cwqmiZhU',
authDomain: 'svelte-todo-20f21.firebaseapp.com',
projectId: 'svelte-todo-20f21',
storageBucket: 'svelte-todo-20f21.appspot.com',
messagingSenderId: '402466412167',
appId: '1:402466412167:web:c739e7eb86fc5b6ac5ca22',
measurementId: 'G-2N348J0NTE'
};
const firebaseApp = initializeApp(firebaseConfig);
export const auth = getAuth(firebaseApp);
export const firestore = getFirestore(firebaseApp);
export default firebaseApp;
My auth.js file:
import { auth } from './firebaseConfig';
import { GoogleAuthProvider, signInWithPopup } from 'firebase/auth';
// Sign in with popup && Google as the provider
const googleProvider = new GoogleAuthProvider();
export const googleSignIn = async () => {
await signInWithPopup(auth, googleProvider)
.then((user) => {
console.log(user);
})
.catch((error) => {
console.error(error);
});
};
And the index.svelte:
<script>
import { googleSignIn } from '../auth';
</script>
<button on:click={() => googleSignIn()}>Sign In</button>
Seems easy enough but I'm getting this error that I can't resolve...
"500
The requested module '/node_modules/.vite/firebase_firestore.js?v=42dbe183' does not provide an export named 'getFirestore'
SyntaxError: The requested module '/node_modules/.vite/firebase_firestore.js?v=42dbe183' does not provide an export named 'getFirestore'"
If it helps, someone suggested that I update my svelte.config.js file to the following...
/** #type {import('#sveltejs/kit').Config} */
const config = {
kit: {
// hydrate the <div id="svelte"> element in src/app.html
target: '#svelte',
vite: {
ssr: {
external: ['firebase']
}
}
}
};
export default config;

An error occurred while creating an application on firebase#9.0.0-beta.2 + NUXT

I create an application with firebase#9.0.0-beta.2
I get the error
Created a folder plugins add file firebase.js
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
const firebaseConfig = {
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: ''
}
let firebaseApp
try {
firebaseApp = getApp()
} catch (e) {
firebaseApp = initializeApp(firebaseConfig)
}
const db = getFirestore(firebaseApp, {})
export { db }
nuxt.config.js
...
plugins: [
'~/plugins/firebase.js'
],
...
I get the error:
error 'getApp' is not defined no-undef
getApp() is not a built-in method and must be called from the appropriate library, in this case: FirebaseApp.getApp()
import { initializeApp, getApps, getApp } from "firebase/app";
getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();
OR
if (FirebaseApp.getApps(context).isEmpty()) {
FirebaseApp.initializeApp(context);
}

firestore vue.js: auth() is not a function

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)

Resources