Firebase (Firestore) Javascript Keep showing error [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Stuck for days now.
Codes are literally copied from the google firebase documentation.
All I want is just write and read data on firestore in firebase console.
Firebase (Firestore) Javascript Keep showing error.
Can anyone help me with code? I don't need fancy code or whatever. Just write and read from firestore that's it.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>
</head>
<body>
<script>
// Firebase App (the core Firebase SDK) is always required and must be listed first
import firebase from "firebase/app";
// If you are using v7 or any earlier version of the JS SDK, you should import firebase using namespace import
// import * as firebase from "firebase/app"
// If you enabled Analytics in your project, add the Firebase SDK for Analytics
import "firebase/analytics";
// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";
// TODO: Replace the following with your app's Firebase project configuration
// For Firebase JavaScript SDK v7.20.0 and later, `measurementId` is an optional field
const firebaseConfig = {
apiKey: "******",
authDomain: "retest-5308a.firebaseapp.com",
databaseURL: "https://retest-5308a-default-rtdb.firebaseio.com",
projectId: "retest-5308a",
storageBucket: "retest-5308a.appspot.com",
messagingSenderId: "125780245080",
appId: "1:125780245080:web:530259dc2a4b1362aae82d",
measurementId: "G-PNTZS15X9K"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
// Initialize Cloud Firestore through Firebase
firebase.initializeApp({
apiKey: "********",
authDomain: "retest-5308a.firebaseapp.com",
projectId: "retest-5308a"
});
var db = firebase.firestore();
db.collection("users").add({
first: "Ada",
last: "Lovelace",
born: 1815
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
</script>
</body>
</html>

You cannot use import firebase from "firebase/app"; inside a script tag in an HTML page.
Instead you should import those SDKs though their own script tags, as you've already done for <script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-app.js"> and firebase-firestore.js.
Once you've added the SDKs through script tags, the imports are no longer needed.

Related

Initialize Firebase realtime database

I have the following code:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import {
getDatabase,
} from "firebase/database";
// 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:
"XXXXXXXXXXXXXXXXXX",
authDomain:
"XXXXXXX-XX-XXXXX.firebaseapp.com",
databaseUrl:
"https://XXXXXXX-XX-XXXXX-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "XXXXXXX-XX-XXXXX",
storageBucket:
"XXXXXXX-XX-XXXXX.appspot.com",
messagingSenderId: "AAAAAAAAAAAA",
appId:
"1:AAAAAAAAAAAA:web:BBBBBBBBBBBBBBB",
measurementId: "G-XXXXXXXXX",
};
// Initialize Firebase
const app = initializeApp(
firebaseConfig
);
const db = getDatabase();
When running my code, Firebase kindly tells me the following:
[2022-11-23T22:45:42.778Z] #firebase/database: FIREBASE WARNING: Database lives in a different region. Please change your database URL to https://XXXXXXX-XX-XXXXX-default-rtdb.europe-west1.firebasedatabase.app (https://XXXXXXX-XX-XXXXX-default-rtdb.firebaseio.com/)
I as a friend of order reads the outputed message and CHANGES the databaseUrl in my code as the one STATED by Firebase in above message.
I then run my code again and get the SAME message. What am I doing wrong?

I am seeing following error while trying to add firebase analytics

I have linked firebase analytics to the firebase project recently but I am getting the following error in my console and nothing is visible in the firebase analytics Dashboard even.
[2022-04-11T06:07:13.736Z] #firebase/analytics: The measurement ID in the local
Firebase config (G-XXXXXXXXX) does not match the measurement ID fetched from the
server (undefined). To ensure analytics events are always sent to the correct Analytics
property, update the measurement ID field in the local config or remove it from the
local config.
This is how I am adding analytics
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "*****************",
projectId: "********",
storageBucket: "*********",
messagingSenderId: "********",
appId: "*******************************",
measurementId: "G-XXXXXXXXX"
};
const app = firebase.initializeApp(firebaseConfig)
const auth = getAuth(app)
const db = getFirestore(app)
firebase.analytics()
const analytics = getAnalytics(app);
console.log(analytics)
Can anyone help what exactly I am missing? Any help is appreciated.
If anyone sees this error, then in my case issue was I have implemented firebase analytics after creating the project not while creating. SO it took 24 hours to reflect. And after 24 hours everything was working.

Firebase .listUsers() is not function

I have been looking for some time, but without answers, so I ask my question:
I work with firebase and I make a function 'getAllUsers' (which must return all registered user uid) :
function getAllusers(nextPageToken){
app.auth().listUsers(1000, nextPageToken)
.then(function(listUsersResult) {
listUsersResult.users.forEach(function(userRecord) {
console.log('user', userRecord.toJSON());
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken);
}
})
.catch(function(error) {
console.log('Error listing users:', error);
});
}
(yes, this is the doc example)
but I get
Uncaught TypeError: app.auth is not a function
I tested :
auth().listUsers()
getAuth.listUsers()
I think this is my imports:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getAuth, signInWithPopup, createUserWithEmailAndPassword, signInWithEmailAndPassword, GoogleAuthProvider, signOut, getAdditionalUserInfo, reauthenticateWithCredential } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-auth.js";
import { getDatabase, set, ref, update, child, onValue, get } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-database.js";
import { getStorage, ref as sRef, uploadBytes, getDownloadURL, deleteObject } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-storage.js";
const firebaseConfig = {
apiKey: "XX",
authDomain: "XX",
databaseURL: "XX",
projectId: "XX",
storageBucket: "XX",
messagingSenderId: "XX",
appId: "XX",
measurementId: "XX"
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth(app);
const storage = getStorage(app);
I am currently researching how to use 'admin' for this
Hoping someone can help me, I keep looking, thanks in advance
The Firebase Admin SDK run code with elevated/administrative permissions and thus can only be used in a trusted environment, such as your development machine, a server that you control, or Cloud Functions/Cloud Run. They cannot be used in client-side application code, as that would be a security concern.
The regular Firebase SDKs only allow a user access to their own profile data, as doing otherwise on an SDK level would be a security concern.
If the application needs to show information about other users, you will have to build (and secure) that yourself on top of Firebase. The two most common options:
Implement the functionality in a custom server-side API that uses the Admin SDK and that you can call from your client-side application code. The custom server-side code you write should then ensure that only data that the caller is authorized to see is returned.
Have each user write to a cloud-hosted database (such as Firestore or the Realtime Database or Firebase), and then have other users read it from there. In this scenario you'll want to use Firebase's security rules to ensure each user can only access the data they're authorized for.
This topic has been covered frequently before, so I recommend also checking out:
Firebase list all users
How do I return a list of users if I use the Firebase simple username & password authentication
Can't retrieve list of all users from firebase authetication
Retrieving a list of users who have registered using Firebase Auth

Firebase multiple "apps" - client side and server side

So, I wanted to add another firebase app into the project. I already had one for SSR (firebase-admin), so server could pre-render sites. Now I want to add firebase#8, so I can start using it on client side, and later apply firestore rules to it. The problem is, when I'm trying to use it I get this error:
/node_modules/#google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/#google-cloud/storage/build/src/index.js
./node_modules/firebase-admin/lib/storage/storage.js
./node_modules/firebase-admin/lib/app/firebase-namespace.js
./node_modules/firebase-admin/lib/default-namespace.js
./node_modules/firebase-admin/lib/index.js
./firebase/config.js
./firebase/createDocument.js
./components/form/Form.js
./pages/opinia/index.js
https://nextjs.org/docs/messages/module-not-found
Here is my config file:
import * as admin from 'firebase-admin';
import firebase from 'firebase';
import 'firebase/firestore';
// initialize firebase on CLIENT
const firebaseConfig = {
apiKey: process.env.FIREBASE_KEY,
authDomain: process.env.FIREBASE_DOMAIN,
projectId: process.env.FIREBASE_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
};
export const clientApp = initializeApp(firebaseConfig);
// firestore
export const projectFirestoreClient = firebase.firestore(clientApp);
// timestamp
export const timestampClient = firebase.firestore.Timestamp;
// initialize firebase on SERVER
if (!admin.apps.length) {
const serviceAccount = require('./firebase-adminsdk.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
// firestore
export const projectFirestoreAdmin = admin.firestore();
// timestamp
export const timestampAdmin = admin.firestore.Timestamp;
So, my question is, how do I fix this error? And what's causing it? Thanks in advance.
Firebase Admin is not meant to be used on client side. When you run the app, Firebase Admin is also being imported and causing that error. Ideally you should initialize Firebase Admin in a different file that can be accessed on server side only.
Checkout this blog for step-by-step explanation on how to use Firebase Admin with NextJS.

I am very confused on how to include Firebase into html

I recently started integrating firebase into my html project, i installed firebase-tools using npm and initialized the project, but then after I included all the scripts mentioned on the firebase website, I used firebase.auth() to sign in the user, then I got an error that firebase is undefined, so I inserted these script tags into my code:
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/firebase/init.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-firestore.js"></script>
and below these I had my firebase config:
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_PROJECT.firebaseapp.com",
databaseURL: "https://MY_PROJECT.firebaseio.com",
projectId: "MY_PROJECT",
storageBucket: "MY_PROJECT.appspot.com",
messagingSenderId: "MESSAGER_ID",
appId: "MY_APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script>
async function signIn(email, password){
await firebase.auth().signInWithEmailAndPassword({
email,
password
}).then(() => {window.location.href = "HomeScreen.html"}).catch((err) => {
document.getElementById('FailedSignIn').style.display = "flex";
})
}
</script>
And then I got these errors:
[2020-03-30T17:24:20.332Z] #firebase/app: Warning: Firebase is already defined in the global scope. Please make sure Firebase library is only loaded once.
Website.htmlAccess to fetch at 'https://firebaseinstallations.googleapis.com/v1/projects/MY_PROJECT/installations' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
https:/…base-analytics.js:1POST https://firebaseinstallations.googleapis.com/v1/projects/MY_PROJECT/installations net::ERR_FAILED
TypeError: Failed to fetch
So I would really appreciate some clarification of the ordering of these script tags, as well as how to properly initialize firebase and use it in my file without any errors.
After you’ve created your account and the Firebase project, all you need to do is add the JavaScript code to your HTML, as described in the Setup Docs
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
// Get a reference to the database service
var database = firebase.database();
// update the variable when the starCount is changed in the database
var starCountRef = database.ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});
// update the UI
function updateStarCount(el, val) {
el.innerHtml(`${val} Stars!`);
}
</script>
Then you can continue to learn about Realtime Database here
The Javascript/Node.JS SDK is introduced here.
How do you start your local web-server at http://localhost:63342?
Maybe you just have to start your web-server with using CORS request headers for external requests.
Example:
yarn serve --cors

Categories

Resources