Firebase Error, application offline (on WebSDK) - javascript

I just create an example for test Firebase Analytics, I worked before with storage capabilities and every works fine.
This is my code:
<button id="test">Press Me</button>
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-app.js';
import {
getAnalytics,
logEvent
} from 'https://www.gstatic.com/firebasejs/9.14.0/firebase-analytics.js';
// Your web app's Firebase configuration
const firebaseConfig = await fetch('../firebaseConfig.json')
.then((response) => response.json());
// Initialize Firebase
const app = initializeApp(firebaseConfig);
// Initialize Analytics and get a reference to the service
const analytics = getAnalytics(app);
const test = document.getElementById('test');
test.addEventListener('click', () => {
console.log('click', analytics);
logEvent(analytics, 'select_content', {
content_type: 'image',
content_id: 'P12453'
});
});
</script>
My Firebase config includes elements below
{
"apiKey": "xxxx",
"authDomain": "yyyyy.firebaseapp.com",
"projectId": "test-firebase-yyyy",
"storageBucket": "yyyyy.appspot.com",
"messagingSenderId": "123456789",
"appId": "1:123465789:web:qazwsxedc",
"measurementId": "G-qwerty"
}
But it throws next error:
FirebaseError: Installations: Could not process request. Application
offline. (installations/app-offline).
Someone could tell me why ? or where to search? As I mention before storage and cloudstore are working fine.
Thank you.

Related

I set getAuth to auth in my html script tag and I am trying to use it in my auth.js but I keep getting an error auth is not defined. How fix?

Here is my index.html.
Oh, and yes, my script tag is inside my body tag.
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js";
// TODO: Add SDKs for Firebase products that you want to use
import { getAuth } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js';
import { getFirestore } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js';
// 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: "HIDDEN FOR THIS POST",
authDomain: "case-study---login-system.firebaseapp.com",
projectId: "case-study---login-system",
storageBucket: "case-study---login-system.appspot.com",
messagingSenderId: "HIDDEN FOR THIS POST",
appId: "HIDDEN FOR THIS POST",
measurementId: "HIDDEN FOR THIS POST"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
// make auth and firestone references
const auth = getAuth(app);
const db = getFirestore(app);
</script>
<!-- Compiled and minified (Materialized)JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- Script-->
<script src="static/auth.js"></script>
<script src="static/index.js"></script>
Here is my auth.js
// Signup
const signupForm = document.querySelector('#signup-form');
signupForm.addEventListener('submit', (e) => {
e.preventDefault();
// get user info
const email = signupForm['signup-email'].value;
const password = signupForm['signup-password'].value;
// sign up the user
auth.createUserWithEmailAndPassword(email,password).then(cred => {
console.log(cred);
});
});
The error I keep getting to the console is:
auth.js:9 Uncaught ReferenceError: auth is not defined
at HTMLFormElement.
When you add type="module" to a <script> tag, it all variables are in the module's own scope - not the global scope like regular <script> tags.
To access auth from static/auth.js, you will need to add auth to the global scope:
// Initialize Firebase
const app = initializeApp(firebaseConfig);
window.analytics = getAnalytics(app);
// make auth and firestone references
window.auth = getAuth(app);
window.db = getFirestore(app);
While this works for simple projects and testing, you should consider moving to using a module bundler like Rollup or WebPack as the documentation recommends.

Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

i have been solving this issue since past 2 days but cant get any idea of how it is solved
const handleSignUp = () => {
auth
.createUserWithEmailAndPassword(email, password)
.then(userCredentials => {
console.log(userCredentials.user.uid)
const user = userCredentials.user;
console.log('Registered with:', user.email);
setDoc(doc(db, "users", "LA"), {
name: "Los Angeles",
// state: "CA",
// country: "USA"
});
})
.catch(error => alert(error.message))
}
The Firebase module is here
if it need any changes of any dependency or any version
please suggest as firebase version is 9.6.11,while firestore is of 3.4.14
// Import the functions you need from the SDKs you need
// import firebase from "firebase";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/database"
// import { getFirestore } from "#firebase/firestore";
import { getFirestore } from 'firebase/firestore'
// import { getFirestore } from 'firebase/firestore/lite'
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()
}
export const auth = firebase.auth()
// export const db = firebase.firestore();
export const db = getFirestore(app)
The error indicates that you are calling setDoc() function to something that is not a DocumentReference or a CollectionReference.
You may try to get the details from the console log as to which variable reference it is hitting the above error and understand why what you are calling it on is not a valid CollectionReference or DocumentReference. Please read through the helpful documentation for Collection Reference
The function setDoc() ,writes to the document referred to by the specified DocumentReference. If the document does not yet exist, it will be created. If you provide merge or mergeFields, the provided data can be merged into an existing document.The result of this write will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.
Also check and verify that you are to call the firebase admin sdk rather than the client SDK and see if that works.
It's an AngularFire version issue, basically if you're using Angular 12, with Firebase 9 you need #angular/fire#^7.0
The compatibility table on the firebase page is key: https://github.com/angular/angularfire#angular-and-firebase-versions
I struggled with this issue for hours ?days? and it was because I had angularfire 7.4 (even 7.2 didn't work).

Could not reach Cloud Firestore backend - React native Firebase v9

I saw many questions on SO regarding this issue and none of them was answered (or the solution doesn't work), I don't know why. People are having this error continuously but no solution is being provided. And from past few days even I'm encountering this error (Note: It seems to be working fine on my physical device (not while debugging, it works on only if I release it), but not on android emulator, so I'm pretty sure my internet is working fine):
Setting a timer for a long period of time, i.e. multiple minutes, is a performance and correctness issue on Android as it keeps the timer module awake, and timers can only be called when the app is in the foreground. See https://github.com/facebook/react-native/issues/12981 for more info.
(Saw setTimeout with duration 3052257ms)
Authorization status: 1
[2022-02-09T07:05:26.500Z] #firebase/firestore: Firestore (9.6.5): Could not reach Cloud Firestore backend. Backend
didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will
operate in offline mode until it is able to successfully connect to the backend.
Authorization status: 1
[2022-02-09T07:08:44.688Z] #firebase/firestore: Firestore (9.6.5): Connection WebChannel transport errored: me {
"defaultPrevented": false,
"g": Y {
"A": true,
"J": null,
"R": [Circular],
"g": $d {
"$": true,
"$a": 2,
"A": 3,
"B": null,
"Ba": 12,
"C": 0,
"D": "gsessionid",
"Da": false,
"Ea": Dd {
"g": Cd {},
},
... & so on...
Package.json:
"#react-native-firebase/app": "^14.3.1",
"#react-native-firebase/messaging": "^14.3.1",
"#react-native-google-signin/google-signin": "^7.0.4",
"expo": "~44.0.0",
"firebase": "^9.6.3",
The authentication & messaging seems to be working fine, but I think the db from firestore is having this issue.
Following is some of the code from my firebase.tsx config file:
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: "",
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = getFirestore(app);
export { auth, db };
What I tried so far:
Changing the firestore database rules as mentioned in this answer: https://stackoverflow.com/a/70980383/11685381
Using this workaround: https://github.com/firebase/firebase-js-sdk/issues/5667#issuecomment-952079600
I'm not using any .env variables according to this answer: https://stackoverflow.com/a/69095824/11685381
Wiped android emulator data, then Cold Boot. Didn't work.
Upgraded firebase-9.6.3 to firebase-9.6.6. Didn't work.
cleaned the build folder, yarn installed all the packages again. Didn't work.
Can anyone provide any working solution to this problem?
Thank you!
EDIT-1:
The code where I'm calling firestore db especially:
In my HomeScreen.tsx:
import { doc, setDoc, onSnapshot, collection } from "firebase/firestore";
import { db } from "../../../firebase";
// inside functional component
useEffect(() => {
const addUser = () => {
const path = doc(db, "Users", user.uid);
const data = {
_id: user.uid,
name: user.displayName,
email: user.email,
};
setDoc(path, data)
.then(() => {
console.log("User added to db");
})
.catch((err) => {
console.log("Error while adding user to firestore: ", err);
});
};
addUser();
}, []);
useEffect(() => {
const unsub = onSnapshot(collection(db, "Items"), (snapshot) =>
setItems(snapshot.docs.map((doc) => doc.data()))
);
return () => unsub();
}, []);
// so nothing is being displayed here as firestore is not working.
Found out the solution on my own after a lot of search. Although I had to make a new bare react native project from scratch, and even then I was encountering that error, I had literally lost hope with firebase at that point. Then after sometime I changed my firebase config to the below code and it worked:
import {initializeApp} from 'firebase/app';
import {getAuth} from 'firebase/auth';
import {initializeFirestore} from 'firebase/firestore';
const firebaseConfig = {
apiKey: '',
authDomain: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
measurementId: '',
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const db = initializeFirestore(app, {
experimentalForceLongPolling: true,
});
export {auth, db};
I had to change the initialization of db as mentioned above, hope it works for everyone out there who's stuck on this weird error.
Thank you all for your help!
First config your db, in firestore.js
import firebase, { initializeApp, getApps, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
let app;
if (getApps().length === 0) {
app = initializeApp(firebaseConfig);
} else {
app = getApp();
}
const db = getFirestore(app);
export { db, auth };
Then add collection to the fireStore DB by:
import {db} from "../firebase.js";
import { collection, addDoc } from "firebase/firestore";
const docRef = await addDoc(collection(db, "chats"), {
chatName: input
}).then(() => {
navigation.goBack();
}).catch((error) => alert(error) );
for Reference: https://firebase.google.com/docs/firestore/quickstart

Can't get data from firebase in react chart

I'm using ApexChartJs for my react project, but when I tried to fetch dynamic data from my firebase database, then show me undefined.
here is my part of code from my project:
import React, { useEffect, useState } from "react";
import Chart from "react-apexcharts";
import { auth, db } from "./firebase";
import { useCollection } from "react-firebase-hooks/firestore";
const [dataPoint, setDataPoint] = useState([]);
const query = db.collection("data");
const [snapshot, loading, error] = useCollection(query);
const [series, setSeries] = useState([]);
useEffect(() => {
setSeries([
{
name: "Desktops",
data: snapshot?.docs.map((doc) => doc.data().value),
},
]);
}, [snapshot]);
console.log(series);
data in the firebase look like:
firebase configure file:
import firebase from "firebase";
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "AIzaSyC2mfjPdIdXxGgJFqqVviw32xoaEMxxxxxx",
authDomain: "chart-app-4591b.firebaseapp.com",
projectId: "chart-app-4591b",
storageBucket: "chart-app-4591b.appspot.com",
messagingSenderId: "995691438244",
appId: "1:995691438244:web:6d945f72ff51d444664631",
measurementId: "G-2B9ZFG6E33",
};
const app = firebase.initializeApp(firebaseConfig);
const db = app.firestore();
const provider = new firebase.auth.GoogleAuthProvider();
const auth = firebase.auth;
export { db, provider, auth };
If your firebase app is well set-up and configured appropriately, the main issue that may lead an undefined query result is that the result are still being loaded.
To overcome this, you should update your series state whenever the loading property changes (along with query result snapshot changes):
const query = db.collection("data");
const [snapshot, loading, error] = useCollection(query);
useEffect(() => {
setSeries([
{
name: "Desktops",
data: snapshot?.docs.map((doc) => doc.data().value),
},
]);
}, [loading, snapshot]);
You should provide alternative error handling as well for state update.
Update (per the permission error)
A common error source would be the lack of privileges to read and write from the configured Firestore DB highlighted by below error message:
FirebaseError: Missing or insufficient permissions
To allow all reads and writes for test only mode (should never be the case for a production system), you can set below Security Rules for the database:
// Allow read/write access to all users under any conditions
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
You can read more on Cloud Firestore Security Rules in the official documentation.

Even if the user is logged in, I get an error

I have a problem:
I want a logged in user to be able to use my getRealtimeUsers function. But I get the following error: FirebaseError: Missing or insufficient permissions.
Below you will find the code. Some explanations:
On the React side, I created a firebase, registered a getRealtimeUsers function there, and tried to use it.
firebase.js file
import firebase from "firebase/app";
import "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID,
measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
};
firebase.initializeApp(firebaseConfig);
export default firebase;
A function that uses the firebase I created:
import firebase from '../../firebase';
export const getRealtimeUsers = () => {
return async () => {
const db = firebase.firestore();
const unsubscribe = db.collection("users")
return unsubscribe;
}
}
Testing of the function
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getRealtimeUsers } from '../redux/actions/chatActions';
import firebase from '../firebase';
let unsubscribe;
class chat extends Component {
componentDidMount() {
unsubscribe = this.props.getRealtimeUsers()
.then(unsubscribe => {
return unsubscribe;
}).catch(error => {
console.log(error);
});
}
componentWillUnmount() {
return () => {
unsubscribe.then(f => f()).catch(error => console.log(error));
}
}
render() {
const ref = firebase.firestore().collection("users");
return (
<div>
check if works
</div>
);
}
}
const mapStateToProps = (state) => ({
});
export default connect(
mapStateToProps,
{
getRealtimeUsers
}
);
Here I let the user do the login
login.js action
export const loginUser = (userData) => (dispatch) => {
axios
.post('/login', userData)
.then((res) => {
console.log(res)
setAuthorizationHeader(res.data.token);
})
.catch((err) => {
console.log(err)
});
};
The login is done on the nodejs side, which is also where I set it to firebase:
const config = {
apiKey: "WqcVU",
authDomain: "c468.firebaseapp.com",
projectId: "c468",
storageBucket: "c468.appspot.com",
messagingSenderId: "087",
appId: "1:087:web:c912",
measurementId: "G-SQX1"
};
;
const firebase = require("firebase");
firebase.initializeApp(config);
// Log user in
exports.login = (req, res) => {
const user = {
email: req.body.email,
password: req.body.password,
};
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
console.log(JSON.stringify(data));
return data.user.getIdToken();
})
.catch((err) => {
console.error(err);
});
};
app.post('/login', login);
the rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
I want only a logged in user to use the getRealtimeUsers function, but even if the user is logged in it doesnt work. That's my problem.
I do not know at all how to solve it
Your case is really problematic, the only way to do security in rules is to access your correntUser or auth. Because you connect through the nodejs, you only return json object and there will be no access to these objects.
For you to have access to these objects what you need to do is connect once more, in react itself, with the same firebase and that's how you enjoy all the worlds that firebase has to offer.
When you log in again, the user does not need to know about it, since when you log in you will reset the password, and choose a random password, it will solve all your problems.
I think this is the most likely solution, but it is not for production
Please update me.
Is there a reason why you're not authenticating directly from the client? The thing is you have to pass in some way the authenticated state from the server to the front...
You have signed in with firebase on your server but you did not sign in with firebase on the front end. Or maybe you did in setAuthorizationHeader(res.data.token); but I'd be curious to know how you did that. It would have been interesting to be able to authenticate with nodejs and then send the tokenId which has been generated, that is data.user.getIdToken(), to the client which the client would then pass to firebase.auth().signInWithToken(token) but this is not possible. If you want to know more about it, I invite you to read this issue (a feature request).
The way to solve this problem is to use Admin SDK and create a custom token.
Firebase gives you complete control over authentication by allowing you to authenticate users or devices using secure JSON Web Tokens (JWTs). You generate these tokens on your server, pass them back to a client device, and then use them to authenticate via the signInWithCustomToken() method.
To achieve this, you must create a server endpoint that accepts sign-in credentials—such as a username and password—and, if the credentials are valid, returns a custom JWT. The custom JWT returned from your server can then be used by a client device to authenticate with Firebase (iOS, Android, web). Once authenticated, this identity will be used when accessing other Firebase services, such as the Firebase Realtime Database and Cloud Storage. Furthermore, the contents of the JWT will be available in the auth object in your Realtime Database Rules and the request.auth object in your Cloud Storage Security Rules.
Here are the steps:
First, you will add the SDK to your server:
yarn add firebase-admin --save
and import it
const admin = require("firebase-admin")
Go over to your Project settings under the "Service accounts" tab.
and click on "Generate a new private key"
a file has been downloaded and saved on your machine. From there, you will either import the file and initialize admin like this:
var serviceAccount = require("/path/to/serviceAccountKey.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
or better yet, in the console
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/serviceAccountKey.json"
and in your file
const credential = admin.credential.applicationDefault() // this will automatically find your env variable
admin.initializeApp({
credential
})
Note: don't forget to set the proper permissions to the private key file with chmod (I had to).
nodejs
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
admin
.auth()
.createCustomToken(data.user.uid)
.then((customToken) => {
console.log('customToken', customToken)
// send token back to client here
res.send(customToken)
})
.catch((error) => {
console.log('Error creating custom token:', error);
});
})
.catch((err) => {
console.error(err);
});
and then on the client:
// get the token and then
firebase.auth().signInWithCustomToken(token)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
});
Another solution would be not using firebase on the client at all and use the backend as some sort of proxy between firebase and the client. The client would make a request to the backend which in turn would interrogate firebase.
in my case, faced same problem with rule's.
please give a try, change your rue and check whether its working or not

Categories