Firebase: No Firebase App '[DEFAULT]' has been created - can't solve - javascript

I started looking into authentication and installed firebase using Node.js, then took the CDN links from the documentation. It worked once on saturday then hasnt worked since.
Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app-compat/no-app).
This is the current look of the file that handels logging in.
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js';
const firebaseConfig = {
apiKey: 'AIzaSyBfb3L9WKUf7qhVyzxpxKBRWUWbcMohUxY',
authDomain: 'study-track-7df2d.firebaseapp.com',
projectId: 'study-track-7df2d',
storageBucket: 'study-track-7df2d.appspot.com',
messagingSenderId: '1015802748429',
appId: '1:1015802748429:web:e7884ea90aec8d73d63f44',
measurementId: 'G-RPCPGGCFV1',
};
const app = initializeApp(firebaseConfig);
const btnCreate = document.querySelector('.create-account');
function googleLogin() {
const provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithPopup(provider)
.then(result =\> {
const user = result.user;
console.log(user);
})
.catch(console.log);
}
btnCreate.addEventListener('click', function (e) {
googleLogin();
});
These are the two CDN calls from the HTML
<script type="module" src="https://www.gstatic.com/firebasejs/9.16.0/firebase-app-compat.js"></script>
<script type="module" src="https://www.gstatic.com/firebasejs/9.16.0/firebase-auth-compat.js"></script>

Related

How to Fix Firebase invalid API key

I'm using my API key stored in a .env.local file. And it setup correctly but not working
assert.ts:128 Uncaught FirebaseError: Firebase: Error (auth/invalid-api-key).
at createErrorInternal (assert.ts:128:1)
at _assert (assert.ts:153:1)
at register.ts:67:1
at Component.instanceFactory (register.ts:90:1)
at Provider.getOrInitializeService (provider.ts:318:1)
at Provider.initialize (provider.ts:242:1)
at initializeAuth (initialize.ts:66:1)
at getAuth (index.ts:44:1)
at Module../src/firebase.init.js (firebase.init.js:22:1)
at Module.options.factory (react refresh:6:1)
I don't know why React is giving me an error. I intialized firebase in the following file
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
// 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
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: process.env.REACT_APP_apiKey,
authDomain: process.env.REACT_APP_authDomain,
projectId: process.env.REACT_APP_projectId,
storageBucket: process.env.REACT_APP_storageBucket,
messagingSenderId: process.env.REACT_APP_messagingSenderId,
appId: process.env.REACT_APP_appId,
measurementId:process.env.REACT_APP_measurementId
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
export default auth;
It is likely that you are having multiple render of your app. Do it this way:
const firebaseConfig = {
apiKey: process.env.REACT_APP_apiKey || 'test',
authDomain: process.env.REACT_APP_authDomain || 'test',
projectId: process.env.REACT_APP_projectId || 'test',
storageBucket: process.env.REACT_APP_storageBucket || 'test',
messagingSenderId: process.env.REACT_APP_messagingSenderId || 'test',
appId: process.env.REACT_APP_appId || 'test',
measurementId:process.env.REACT_APP_measurementId || 'test'
};
In that case at the first render, when the environment variables are yet available, you will have default values, not null or undefined values.
I hope it helps someone.

Error get FCM token on firebase version 9

yesterday my application had no problems when it wanted to request fcm tokens, suddenly now it can't, and the error that appears is:
error result
my assumption is because firebase-messaging-sw can't be active, it's not even in the build result folder, even though yesterday there was no problem at all. the firebase I'm using is version 9 so it's modular.
firebase-messaging-sw.js
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging/sw";
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
const firebaseApp = initializeApp({
apiKey: "--------",
authDomain: "-------",
projectId: "------",
storageBucket: "-----",
messagingSenderId: "------",
appId: "---------"
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = getMessaging(firebaseApp);
main.js
import { createApp } from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store'
import { initializeApp } from "firebase/app";
import './utils/firebase-messaging-sw'
import { getMessaging, getToken } from "firebase/messaging";
const firebaseConfig = {
apiKey: "---------------------",
authDomain: "-----------------------",
projectId: "---------------------",
storageBucket: "----------------------",
messagingSenderId: "-----------------------",
appId: "---------------------------"
};
const app = initializeApp(firebaseConfig);
const messaging = getMessaging();
getToken(messaging, { vapidKey: '---------------------------------' }).then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
createApp(App).use(store).use(router).mount('#app')
after build the firebase-messaging-sw.js file should also be in it, that's what happened yesterday, but somehow now suddenly it can't
build result
because i use pwa, there should be 2 active service workers
service worker from Vue
service worker from firebase-messaging-sw
in fact the only active ones are vue's service workers
active service workers
here is my directory structure
directory

How to read/retrieve data from Firebase using Javascript

I am trying to get my datas from firebase with console log but i am getting an error.
The error is: image
This is my database: https://i.stack.imgur.com/A1zYm.png
<script type="module">
import {
initializeApp
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import {
getDatabase,
set,
ref,
update
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
import {
getAuth,
createUserWithEmailAndPassword,
signInWithEmailAndPassword,
onAuthStateChanged,
signOut
} from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
const firebaseConfig = {
apiKey: ,
authDomain: ,
databaseURL: ,
projectId: ,
storageBucket: ,
messagingSenderId: ,
appId: ,
measurementId:
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
const auth = getAuth();
const firebaseRef = firebase.database().ref("Users");
firebaseRef.once("value", function(snapshot) {
snapshot.forEach(function(element) {
console.log(element);
})
});
</script>
You're trying to use the old v8 syntax with Firebase SDK 9, which won't work. You'll either have to use the new modular syntax, or import the older SDKs or the compatibility versions on v9.
In v9 syntax, getting a reference to and reading a value from the database is done with:
import { getDatabase, ref, get } from "firebase/database";
...
const database = getDatabase();
const firebaseRef = ref(database, "Users");
get(firebaseRef, function(snapshot) {
snapshot.forEach(function(element) {
console.log(element);
})
});
For more examples, see the Web version 9 (modular) tabs in the documentation I linked above, and the upgrade guide specifically the section on upgrading with the compat libraries.

how to solve const auth not defined?

i want to use firebase authentication, so i declared a constant named auth in my html body script and i wanted to use it in my auth.js file but it say it's not defined and i want to know how to solve the probleme.
this is the code i wrote:
this is the code in my html file:
<!-- Firebase -->
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-analytics.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-auth.js";
import { getFirestore } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-firestore.js";
// TODO: Add SDKs for Firebase products that you want to use
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyC3GLIN5TBmCDoTfy0dEOgOdvVvqNw-ric",
authDomain: "auth-project-38aaa.firebaseapp.com",
projectId: "auth-project-38aaa",
storageBucket: "auth-project-38aaa.appspot.com",
messagingSenderId: "431888894254",
appId: "1:431888894254:web:71bb9b250fbb8a21edd2bf",
measurementId: "G-6BBPCJ3814"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = getAuth(app);
const db = getFirestore(app);
</script>
<!-- JS -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="js/auth.js"></script>
and this is the code in my auth.js:
const signUpForm = document.querySelector('#register-form');
signUpForm.addEventListener('submit', (e) => {
e.preventDefault();
// get user info
const name = signUpForm['name'].value;
const email = signUpForm['email'].value;
const pass = signUpForm['pass'].value;
const rePass = signUpForm['re_pass'].value;
const agreeTerm = signUpForm['agree-term'].value;
console.log(name, email, pass, rePass, agreeTerm);
// sign up the user
auth.createUserWithEmailAndPassword(email, pass).then(cred => {
console.log(cred);
});
});
The auth.createUserWithEmailAndPassword is for the Firebase SDK v8 and earlier, or for compat mode in v9.
The new syntax is according to the documentation on creating a user:
createUserWithEmailAndPassword(auth, email, pass).then(cred => {
...
});

Firebase - Failed to get document because the client is offline (v9 Upgrade)

Recently upgraded to firebase v9 from v8 in my React Native project and I am now unable to use my legacy v8 firestore methods.
The error I am receiving is:
[Unhandled promise rejection: FirebaseError: Failed to get document because the
client is offline.]
I initialize firebase in a file I call fire-config.js. The commented //import firebase from 'firebase'; is how I previously imported firebase in v8.
I then would import fire from fire-config.js into my controller methods. Ex: userController.js.
I tried a couple different combinations of /compat and /compat/app to no avail. I was following the upgrade guide (https://firebase.google.com/docs/web/modular-upgrade) which my understanding was update the path and that was all that was needed.
Package.json:
"firebase": "9.0.2",
fire-config.js
//import firebase from 'firebase';
import firebase from 'firebase/compat';
require("firebase/functions");
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "XXXXX",
authDomain: "XXXXX",
databaseURL: "XXXX",
projectId: "XXXX",
storageBucket: "XXXX",
messagingSenderId: "XXXXX",
appId: "XXXX",
measurementId: "XXXXX"
};
try {
firebase.initializeApp(firebaseConfig);
} catch(err){
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)}
}
const fire = firebase;
export {fire};
userController.js
import {fire} from "../config/fire-config";
const getUserDetail = async (user) => {
let userDetail = {};
await fire
.firestore()
.collection("users")
.doc(user.uid)
.get()
.then((doc) => {
if (doc.exists) {
userDetail = {
id: doc.id,
...doc.data(),
};
}
});
return userDetail;
};

Categories

Resources