Firebase authentication error in javascript - javascript

I'm encountering an error when trying to add a user to firebase authentication. The const auth is defined before the script is loaded. I've tried calling with and without the app parameter. The user is not being added and I can't seem to figure this error out. I've cut out only the code I think is relevant. Apologies if this is a stupid question, I'm just diving into HTML and JS.
Error: Uncaught ReferenceError: auth is not defined
at HTMLFormElement. (auth.js:12)
From html file:
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-auth.js";
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
<script src="js\auth.js"></script>
From js file:
auth.createUserWithEmailAndPassword(email, password).then(cred => {
console.log(cred);
});

You're using the modular SDK, which means that imported names are no longer added to a global namespace. If your include file (js.auth.js) needs access to the auth service, you will need to import getAuth into that file too and initialize it there as well.

Related

Failed to resolve 'firebase'

I am struggling to get started with Firebase auth in my web application. I am following this tutorial. I installed Parceljs to be able to run the app locally. When I add the line var firebase = require('firebase'); I get the error #parcel/core: Failed to resolve 'firebase' from './app.js' How do I fix this?
I include the js code in my index.html like so:
<script type="module" src="app.js"></script>
If I comment out var firebase = require('firebase'); the code compiles (parcel). The row below seems fine (var firebaseui = require('firebaseui'); ) though.
I was able to bypass the error a bit by commenting out the row that gave the error and replacing it with import { getAuth } from 'firebase/auth';. Then I had to change the code for initialising the Firebase UI widget like so:
const app = initializeApp(firebaseConfig);
// Initialize the FirebaseUI Widget using Firebase.
var ui = new firebaseui.auth.AuthUI( getAuth(app) );
But when I specify the FirebaseUI configuration I get the error Uncaught ReferenceError: firebase is not defined in the browser console on the row firebase.auth.GoogleAuthProvider.PROVIDER_ID. So I come back to the same problem not being able to run var firebase = require('firebase');

Uncaught SyntaxError: Cannot use import statement outside a module (Using Firebase)

I'm having a problem storing data to my database through my html form, The error I get comes from my import statement which is: Uncaught SyntaxError: Cannot use import statement outside a module!
Code below:
import {
initializeApp
} from "firebase/app";
const firebaseConfig = {
apiKey: "MY_API_KEY", //actual values are in my code, changed here for security purposes.
authDomain: "My_auth_Domain",
databaseURL: "FirebaseDb_URL",
projectId: "Project_id",
storageBucket: "storageBucket",
messagingSenderId: "SenderId",
appId: "appId"
};
const app = initializeApp(firebaseConfig);
let inviteInfo = firebase.database().ref("inviteinfos");
document.getElementById("#regform", submitForm);
function submitForm(e) {
let name = document.getElementsByName("fullname").value;
let compName = document.getElementsByName("compName").value;
let email = document.getElementsByName("email").value;
let address = document.getElementsByName("address").value;
let contact = document.getElementsByName("contact").value;
console.log(name, compName, email, address, contact);
saveContactInfo(name, compName, email, address, contact);
document.getElementById("#regform").reset();
}
What I have tried so far:
changed import statement to the following
const {initializeApp} = require("firebase/app");
used import with firebase provided link
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
used const with the firebase provided link:
const {initializeApp} = require("https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js");
Moved js from app.js into the main html page with a script tag of type module.
used npm to install firebase to retrieve the modules.
in regards to the link based solution I tried to remove the -app to see if it made a difference but it did not.
So far none of these have worked for me, the table I am trying to store information to currently does not exist but research has shown that running even without the table existing will create the table automatically for me.
Load app.js like this:
<script type="module" src="./app.js"></script>
Inside app.js, you import firebase-app like this:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
// ...
Here's an example (I can't use a separate file for app.js, but this demonstrates that it does work):
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
// Check that it worked and returned a function:
console.log(typeof initializeApp); // "function"
</script>
You don't need a script tag for firebase-app.js at all, it'll get loaded by the browser because of your import.
Note that this will be using modules natively in the browser. All modern browsers directly support doing that, but obsolete ones like Internet Explorer don't, and separately loading modules like this can involve lots of small HTTP calls rather than a few larger ones, which can cause page load delays even with modern net protocols like SPDY. For that reason, people often use bundlers like Vite, Rollup, Webpack, etc. that combine modules into a small number of bundle files. If you like, you could look at doing that. But again, modern browsers natively support modules, so you don't have to.
Using "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js" in every place you want to import from firebase-app may be a bit of a pain. You have two options to make it easier:
1. In Chromium-based browsers (only, sadly, for now), you can use an import map:
<script type="importmap">
{
"imports": {
"firebase-app": "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js"
}
}
</script>
That tells your browser that when you import from "firebase/app", it should use "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js".
Live Example:
<script type="importmap">
{
"imports": {
"firebase/app": "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js"
}
}
</script>
<script type="module">
import { initializeApp } from "firebase/app";
// Check that it worked and returned a function:
console.log(typeof initializeApp); // "function"
</script>
2. If you can't use import maps, you can write a module that re-exports everything from firebase-app, and then import from that module in your code rather than directly from firebase-app:
Your own local firebase-app.js file:
// This re-exports all of its named exports (but not its default, if any)
export * from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
/* firebase-app.js doesn't provide a default export. If it did, this is
how you'd re-export it:
export { default } from "https://www.gstatic.com/firebasejs/9.6.6/firebase-app.js";
*/
Then app.js would use firebase-app.js:
import { initializeApp } from "./firebase-app.js";
(I can't do a live example of that with Stack Snippets, but here's that on CodeSandbox.)

Firebase auth and firestore functionalities not working

I am using firebase for the backend part of my application.
My code goes like this:
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import {getFirestore,collection,getDocs} from 'firebase/firestore/lite'
// Your web app's Firebase configuration
const firebaseConfig = {
//My app's Config object...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
</script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-firestore.js"></script>
auth script:
const auth=firebase.auth();
const db=firebase.firestore();
I am getting these errors in the browser console:
Uncaught SyntaxError: Unexpected token 'export'
Uncaught SyntaxError: Cannot use import statement outside a module
Uncaught SyntaxError: Cannot use import statement outside a module
Uncaught ReferenceError: firebase is not defined
at auth.js:1
Can someone pls help me!
Since version 9 of its JavaScript SDK, Firebase has changed the way you call its modules. These two lines in your code are for the v8 and before SDKs:
const auth=firebase.auth();
const db=firebase.firestore();
The equivalent for v9 and above is:
const auth = getAuth();
const db = getFirestore()
I recommend checking out the Firebase documentation, which contains examples for both SDK variants, the upgrade guide for the v9 SDK, and this blog post on the modular SDK design

Uncaught SyntaxError: The requested module 'https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js' does not provide an export named 'default'

I'm trying to set up and test google authentication for a webapp I'm working on. I've been having a lot of issues with getting the javascript functions running, and I'm not sure why. I use all CDN imports because I was having an error referencing firebase folders locally. Here are my files:
firebase-config.js
// Import the functions you need from the SDKs you need
import firebase from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.0/firebase-analytics.js";
const firebaseConfig = {
[config keys]
};
// Initialize Firebase app
const fb_app = firebase.initializeApp(firebaseConfig); // returns an app
const analytics = getAnalytics(app);
export {fb_app};
signin.js
import {fb_app} from "/src/firebase-config.js";
import { getAuth, signInWithPopup, GoogleAuthProvider } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
fb_app; // I was getting an error that the firebase app isn't initialized, so I placed this here to see if it was work. I am not sure this is the correct way to call the app in this file.
const auth = getAuth();
const provider = new GoogleAuthProvider();
signInWithPopup(auth, provider)
.then((result) => {
console.log("Signing User In...");
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
// ...
}).catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
document.getElementById("signInButton").onclick = signInWithPopup(auth, provider); // this is how I am importing the function to the html.
index.html
<body>
<div class="loginbox">
<h1>Login</h1>
<form>
<div id="google-signin">
<button id="signInButton">Login with Google -></button>
</div>
</form>
</div>
<!-- <script src="https://unpkg.com/react#17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom#17/umd/react-dom.development.js" crossorigin></script>
<script src="/src/signin.jsx"></script> -->
</body>
Any help whatsoever would be appreciated. I am very new to learning this stuff, so I understand if I may have unintentionally done something wrong. I have gotten a lot of different errors relating to smaller minor details, but I genuinely don't understand why this error would be arising. Thank you in advance.
you need more details about the libraries you are using. the error originates here
import firebase from "https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js";
you are trying to import the default object from the library by not using the parenthesis import. which is not provided from the firebase library.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Firestore arrayUnion

I'm building a basic CRUD app with vue.js and firebase. I'm trying to build out a favorites functionality and have ran into a persistent problem storing the data.
When a using clicks the add to favorites button I'm attempting to add the document id to an array in a "user profile" document. Here's the code:
export function addNewUserAction (type, key, userID){
console.log(userID);
console.log(key);
firebase.firestore().collection('userActions').add({
type: type,
listing: key,
user: userID,
time: Date.now()
})
if(type === 'favorite'){
var sendfav = db.collection('userProfiles').doc(userID).update({
favs: firebase.firestore.FieldValue.arrayUnion(key)
});
}else if(type === 'xout'){
var sendxout = db.collection('userProfiles').doc(userID).update({
xouts: firebase.firestore.FieldValue.arrayUnion(key)
});
}else{
console.error(type + " is not a user action");
}
}
I get the following error in the console:
Uncaught TypeError: Cannot read property 'arrayUnion' of undefined
at addNewUserAction
I have firebase and the db ref imported, and have ran a bogus .set() through each reference to confirm they are pointing at the right spots. I also already have the arrays created in 'userProfile' document.
The firebase install is fresh, like last week fresh, so I should have the function in my build.
Seems that arrayUnion is just not working. Any ideas? The other firestore functions are workin so I'm not sure. Am I blatenly missing something? Thanks
If you are using the Admin SDK
I was having some random errors similar to this, among others as I was experimenting. It turns out it was because I was using firebase admin sdk which requires a slight change compared to the web SDK documentation. If you are using firebase admin, replace
firebase.firestore.FieldValue.arrayUnion(...
with
admin.firestore.FieldValue.arrayUnion(...
I had the same issue...
This would not work
import { fireStore } from '../../firebase';
....
fireStore.collection("users").doc(props.uid).update({
points: fireStore.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});
I changed the import and used the exact code from the Firebase Docs.
This works fine.
import * as firebase from 'firebase';
....
fireStore.collection("users").doc(props.uid).update({
points: firebase.firestore.FieldValue.arrayUnion({value: pointObj.value, reason: pointObj.reason})
});
Hope that helps.
Just wanted to update this. I was able to get this working by importing firebase the following way:
`import firebase from "firebase/firebase";`
I think my issue before was several problems, the first primarily was not having the correct version. I just recently updated to 5.8.4 which completely broke my app. I tried the above as a possible solution and it got my app working again. That led me to try it on with arrayUnion and it worked. Hopefully thats helpful to someone. Thanks all for the help.
Update 10/11/19
So I wanted to add another update to this in case someone new to firebase is chasing their tail with this as I have been.
So the solution I included above works because it uses the entire firebase SDK package ('firebase/firebase') which is fine, however you will importing the entire firebase package which is not ideal. You constantly see an alert in your console that you're using the development SDK
If you're trying to optimize your app and only import the firebase packages you need ( i.e. auth, datatbase, etc.) you need to import the firebase app object from 'firebase/app' then import the required packages. The key is to import as an object as the firebase docs call for:
import * as firebase from 'firebase/app';
Import 'firebase/auth'
If you use:
import firebase from 'firebase/app' this will not work.
Hope that helps someone. I know it's probie stuff but it stumped me for a while in my learning curve.
Firestore - Pass Array To arrayUnion()
let myArray = ["1", "2", "3"];
docRef.update({
test: firebase.firestore.FieldValue.arrayUnion.apply(this, myArray)
});
This worked for me^
For Vue.js Developers
I have created a folder named firebase in src folder, then i have created a file named init.js in firebase folder
init.js
import * as firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
// Your Firebase Config
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
// utils
const db = firebase.firestore();
const auth = firebase.auth();
export { db, auth, firebase };
Now use them in whichever components you need.
Just by,
import { firebase, auth, db } from "#/firebase/init.js";
Now You can use firebase without any Errors
db.collection("users") // Collection Name
.doc(userId) // Document in Collection indexed userId
.update({
friends: firebase.firestore.FieldValue.arrayUnion(auth.currentUser.uid)
})
// friends is the array collection in firestore
Thats It

Categories