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 => {
...
});
Related
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>
My Firebase Function runs in the emulator and writes to the same collection and document:
import * as functions from "firebase-functions";
export const MakeUppercase = functions.firestore.document('Messages/{docId}').onCreate((snap, context) => {
try {
const original = snap.data().original;
const uppercase = original.toUpperCase();
return snap.ref.set({ uppercase }, { merge: true });
} catch (error) {
console.error(error);
}
});
That works great. Now I want to write to a different collection in the Firestore emulator:
import { initializeApp } from "firebase/app";
import * as functions from "firebase-functions";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
const firebaseConfig = {
apiKey: "...",
authDomain: "triggerable-functions-project.firebaseapp.com",
projectId: "triggerable-functions-project",
storageBucket: "triggerable-functions-project.appspot.com",
messagingSenderId: "...",
appId: "..."
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
connectFirestoreEmulator(db, 'localhost', 8080);
export const MakeUppercase = functions.firestore.document('Messages/{docId}').onCreate((snap, context) => {
try {
const original = snap.data().original;
const uppercase = original.toUpperCase();
return db.firestore().collection('AnotherCollection').doc(context.params.docId).set({ uppercase }, { merge: true });
} catch (error) {
console.error(error);
}
});
That throws this error:
TypeError: db.firestore is not a function
I either have an incorrect Firestore DocumentReference or I didn't import a necessary module.
Let's write to Cloud Firestore. Same code, new module, different DocumentReference:
import * as admin from "firebase-admin";
...
return admin.firestore().collection('AnotherCollection').doc(context.params.docId).set({ uppercase }, { merge: true });
Same error:
TypeError: admin.firestore is not a function
Let's write to the Storage emulator:
import { getStorage, connectStorageEmulator, ref, uploadString } from "firebase/storage";
...
const storage = getStorage();
connectStorageEmulator(storage, "localhost", 9199);
...
return storage.collection('AnotherCollection').doc(context.params.docId).set({ uppercase }, { merge: true });
That throws the same error:
TypeError: storage.collection is not a function
Let's write to Cloud Storage:
const storageRef = ref(storage, 'Messages');
...
return uploadString(storageRef, uppercase);
The log says that the function executed without errors but when I go to Firebase Console I don't see the file in Cloud Storage.
Here's my final code. Why is app declared but never used?
import { initializeApp } from "firebase/app";
import * as functions from "firebase-functions";
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
import { getStorage, connectStorageEmulator, ref, uploadString } from "firebase/storage";
import * as admin from "firebase-admin";
const firebaseConfig = {
apiKey: "...",
authDomain: "triggerable-functions-project.firebaseapp.com",
projectId: "triggerable-functions-project",
storageBucket: "triggerable-functions-project.appspot.com",
messagingSenderId: "...",
appId: "..."
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
connectFirestoreEmulator(db, 'localhost', 8080);
const storage = getStorage();
const storageRef = ref(storage, 'Messages');
connectStorageEmulator(storage, "localhost", 9199);
export const MakeUppercase = functions.firestore.document('Messages/{docId}').onCreate((snap, context) => {
try {
const original = snap.data().original;
const uppercase = original.toUpperCase();
return uploadString(storageRef, uppercase);
} catch (error) {
console.error(error); // emulator always throws an "unhandled error": "Your function timed out after ~60s."
}
});
You're using the new(ish) modular syntax of the v9 and later SDKs when you call getFirestore. With that new API, most calls are no longer namespaced, but are top-level functions. So there are no longer any public methods on the db object you have (as the error message says), but instead you have to pass the db object when calling those top-level functions.
The equivalent of this code:
db.firestore().collection('AnotherCollection').doc(context.params.docId).set({ uppercase }, { merge: true });
Would be:
setDoc(
doc(db, 'AnotherCollection', context.params.docId),
{ uppercase }, { merge: true })
)
Which is pretty close to the code sample in the documentation on setting a document with the v9 syntax, so I recommend keeping that handy while converting the rest of the code to the new API. The Upgrade from version 8 to the modular Web SDK guide is also a good place to get started, as are the blog posts Introducing the new Firebase JS SDK and The new Firebase JS SDK is now GA
Thanks, #Frank van Puffelen! Here's my Firebase version 9 code for writing to a different directory in the emulator:
import { initializeApp } from "firebase/app";
import * as functions from "firebase-functions";
import { getFirestore, connectFirestoreEmulator, setDoc, doc } from "firebase/firestore";
const firebaseConfig = {
apiKey: "...",
authDomain: "triggerable-functions-project.firebaseapp.com",
projectId: "triggerable-functions-project",
storageBucket: "triggerable-functions-project.appspot.com",
messagingSenderId: "...",
appId: "..."
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
connectFirestoreEmulator(db, 'localhost', 8080);
export const MakeUppercase = functions.firestore.document('Messages/{docId}').onCreate((snap, context) => {
try {
const original = snap.data().original;
const uppercase = original.toUpperCase();
return setDoc(
doc(db, 'AnotherCollection', context.params.docId),
{ uppercase }, { merge: true }
);
} catch (error) {
console.error(error);
}
});
Commenting out the emulator
connectFirestoreEmulator(db, 'localhost', 8080);
writes to Cloud Firestore. This threw an error:
Connection GRPC stream error. Code: 7 Message: 7 PERMISSION_DENIED: Missing or insufficient permissions.
I'm not going to worry about that, I presume that the emulator isn't intended to write to the Cloud.
As for Storage, my original code executes without errors but nothing writes to Storage in the emulator. Trying Cloud Storage, my Firebase Console refuses to set up Storage.
The documentation explains why I kept getting "not a function" errors. Instead of thinking of a Firestore location as a place with an address (in the namespace), in version 9 Firestore locations are functions with parameters.
While the version 8 APIs are based on a dot-chained namespace and
service pattern, version 9's modular approach means that your code
will be organized principally around functions.
David East explained in a blog post that the old (version 8) Firebase managed namespaces on the window but version 9 uses ES modules:
Historically libraries have been loaded and managed via a namespace on
the window, such as window.firebase. This technique does not allow for
tree shaking and lacks other benefits of the JavaScript module system.
I am trying to integrate firebase with ReactJs like this.
Here is my code
import firebase from "firebase";
var firebaseConfig = {
apiKey: "", // Add API Key
databaseURL: "" // Add databaseURL
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
export const db = firebase;
var firepadRef = firebase.database().ref();
export const userName = localStorage.getItem('auth_name');
const urlparams = new URLSearchParams(window.location.search);
const roomId = urlparams.get("id");
if (roomId) {
firepadRef = firepadRef.child(roomId);
} else {
firepadRef = firepadRef.push();
}
export default firepadRef;
And now I get this warning:
It looks like you're using the development build of the Firebase JS
SDK. When deploying Firebase apps to production, it is advisable to
only import the individual SDK components you intend to use.
For the module builds, these are available in the following manner
(replace with the name of a component - i.e. auth, database,
etc):
CommonJS Modules: const firebase = require('firebase/app');
require('firebase/');
ES Modules: import firebase from 'firebase/app'; import
'firebase/';
Typescript: import firebase from 'firebase
After a new firebase.initializeApp, (assuming you are using v9 of firebase), you need to instantiate the db differently. Check your docs. I'd write your code like this instead:
// firebase file which you export the initialization
import firebase from "firebase";
var firebaseConfig = {
apiKey: "", // Add API Key
databaseURL: "" // Add databaseURL
};
// Initialize Firebase
var fire = firebase.initializeApp(firebaseConfig);
export fire.
//second js file
import firebase from ./firebase.js
import {getDatabase, ref, set} from "firebase/database";
var db = getDatabase(Firebase);
export const userName = localStorage.getItem('auth_name');
const urlparams = new URLSearchParams(window.location.search);
const roomId = urlparams.get("id");
//if you want to push to the db or something, you call the method
set(ref(db, 'users/' + userId), {
username: name,
email: email,
profile_picture : imageUrl
});
//more code here
All in all check the docs one more time. and use version 9, its implementation is the best.
https://firebase.google.com/docs/database/web/read-and-write#web-version-9_1
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.
I am trying to read/write data from my database, but I always get this error:
firebase.database.ref is not a function error
Here is how I have included firebase into a project:
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-database.js"></script>
then:
<script>
var config = {
...
};
firebase.initializeApp(config);
</script>
The Firebase Auth works correctly. But when I do this:
function insertUser(user,name) {
var ref = firebase.database.ref();
ref.collection("users").doc(user.uid).set({
uid: user.uid,
email: user.email,
name: name
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
I get error above. What am I doing wrong?
database() is a method so change it to the following:
var reference = firebase.database().ref();
Also better not to have same variable and method name.
I also get a database function not found issue with latest firebase library. After researching what I found is, It is due to Javascript I am importing for the database:
Previously I was using below script, Which was not working:
<script src="https://www.gstatic.com/firebasejs/7.16.0/firebase-app.js"></script>
After removing -app from the script URL, it start working:
<script src="https://www.gstatic.com/firebasejs/7.16.0/firebase.js"></script>
Hope this will be helpful for others.
If you are importing firestore (database) module into the some React component make sure you will import "firebase/database" and export export const firestore = app.database() in main firebase file
Firebase.tsx
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/database"
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
})
export const firestore = app.database()
export const auth = app.auth()
export default app
myComponent.tsx
import React from "react";
import {firestore} from '../../../Firebase'
export default function Home() {
const db = firestore.refFromURL("https://<project>.firebaseio.com")
return (
...
)
}
I ran into the same problem. I just added this CDN
<script src="https://www.gstatic.com/firebasejs/8.0.1/firebase-database.js"></script>