Web/Firebase - I cannot access the realtime database - javascript

I cannot read or write to the firebase real-time database... please help.
I have set my rules to both read and write 'true', and I've tested it in the playground.
I'm using the create-react-app boilerplate setup.
My version of the firebase is 9.6.4
Here's my firebase file
import { initializeApp } from 'firebase/app';
import { getDatabase, set, ref } from 'firebase/database';
const firebaseConfig = {
apiKey: 'AIzamGZ1LBAAtb',
authDomain: 'helpme.firebaseapp.com',
databaseURL: 'https://helpme.firebaseio.com',
projectId: 'helpme',
storageBucket: 'helpme.appt.com',
messagingSenderId: '93help1',
appId: '1:293268271119:web:d4e9e73help',
measurementId: 'helpKQLWS',
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
set(ref(db, 'chatroom'), {
name: '',
createdAt: '',
photo: '',
});

Related

#firebase/app-check: AppCheck: Requests throttled due to 400 error. Attempts allowed again after 00m:01s (appCheck/throttled)

I have just set up my app and integrated appcheck
and the code looks like
import { initializeApp, getApps } from "firebase/app";
import { getAuth, } from "firebase/auth";
import { getAnalytics } from "firebase/analytics";
import { getFirestore } from "firebase/firestore";
let app;
if (!getApps().length) {
app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
});
}
async function initialize() {
const { initializeApp } = require("firebase/app");
const { initializeAppCheck, ReCaptchaV3Provider } = require("firebase/app-check");
const app = initializeApp({
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
databaseURL: process.env.NEXT_PUBLIC_DATABASE_URL,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
});
return initializeAppCheck(app, {
provider: new ReCaptchaV3Provider(process.env.NEXT_PUBLIC_APP_CHECK_KEY),
isTokenAutoRefreshEnabled: true
});
}
if (typeof window !== "undefined") {
initialize().then((res)=>{
// console.log(res)
}).catch((err)=>{
throw(err)
})
}
export const auth = getAuth();
export const db = getFirestore();
export default app;
So when i set isTokenAutoRefreshEnabled to true, the error comes up and when I set it to false everything works.
I am using firebase ^9.9.4 and this gives the above error so I decided to downgrade and use firebase ^9.8.2 since I had set up a different project the same way and there were no errors. In this version, I get the error
FirebaseError: AppCheck: Fetch server returned an HTTP error status. HTTP status: 400. (appCheck/fetch-status-error).
at exchangeToken
What is this error and how can I fix it

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.

httpsCallable is not defined when using Firebase Cloud Functions

For the past week I've been trying to setup Firebase Cloud Functions, but have been unable to import the dependencies needed.
This is in my script.js file, my main code:
import firebase from "firebase/app"
require("firebase/functions");
const testFunction = httpsCallable(functions, 'testFunction')
That returns this error:
script.js:7 Uncaught ReferenceError: httpsCallable is not defined
at Object.parcelRequire.script.js.firebase/app (script.js:7)
at newRequire (script.75da7f30.js:47)
at script.75da7f30.js:81
at script.75da7f30.js:120
In my index.html, I have this:
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-functions.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.10.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.6.5/firebase-analytics.js"></script>
<script>
const firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXX-XXXXX.firebaseapp.com",
databaseURL: "https://XXXXX-XXXXX-default-rtdb.firebaseio.com",
projectId: "XXXXX-XXXXX",
storageBucket: "XXXXX-XXXXX.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXXXXX:web:XXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
firebase.analytics()
</script>
What am I missing?
Edit: To upgrade to the new version of Firebase, I removed the script references in my html, did "npm i firebase#9.1.3" in my project folder, moved everything to my script.js file, and this is what it looks like now. But I still get the httpsCallable is not defined error, so the version didn't seem to affect it.
import firebase from "firebase/compat/app"
import 'firebase/compat/functions'
import 'firebase/compat/auth'
import 'firebase/compat/analytics'
import 'firebase/compat/database'
const firebaseConfig = {
apiKey: "XXXXXXXXXXXX",
authDomain: "XXXXX-XXXXX.firebaseapp.com",
databaseURL: "https://XXXXX-XXXXX-default-rtdb.firebaseio.com",
projectId: "XXXXX-XXXXX",
storageBucket: "XXXXX-XXXXX.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXXXXX:web:XXXXXX"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
firebase.analytics()
When using the legacy namespaced syntax (<v8 & v9 compatibility-mode), use:
import firebase from "firebase/compat/app" // just firebase/app in <v8
import 'firebase/compat/functions' // just firebase/functions in <v8
const testFunction = firebase.functions().httpsCallable('testFunction')
testFunction({ /* data */ })
.then((result) => { /* ... */ })
.catch((err) => { /* ... */ })
For the modern modular syntax (v9+), use:
import { getFunctions, httpsCallable } from 'firebase/functions'
const testFunction = httpsCallable(getFunctions(), 'testFunction')
testFunction({ /* data */ })
.then((result) => { /* ... */ })
.catch((err) => { /* ... */ })
These are documented here.

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;
};

How to import firebase in service worker?

Here is my code. I do not know why I get an error. Here is the part of my code where I want to use it:
importScripts('https://www.gstatic.com/firebasejs/3.7.4/firebase.js');
var firebaseConfig = {
apiKey: xxxxxxxxxxx,
authDomain: xxxxxxxxxxxxx,
databaseURL: xxxxxxxxxxxxxxxxxx,
projectId: xxxxxxxxxxx,
storageBucket: xxxxxxxxxx,
messagingSenderId: xxxxxxxxxxxx,
appId: xxxxxxxxxxxxxxxxx
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
Try This,
import firebase from 'firebase'
const config = {
apiKey: xxxxxxxxxx,
authDomain: xxxxxxxxxx,
databaseURL: xxxxxxxxxx,
projectId: xxxxxxxxxx,
storageBucket: xxxxxxxxxx,
messagingSenderId: xxxxxxxxxx
appId: xxxxxxxxxx
};
firebase.initializeApp(config);
firebase.firestore().settings({});
export default firebase;
Add web application platform to the firebase console or project from there you find config information and add it in code.

Categories

Resources