Reactjs backend connection issue - reactjs

My problem is that my browser is showing that fire store is not able to connect to the backend:
#firebase/firestore: Firestore (9.1.1): Could not reach Cloud Firestore backend. Connection failed 1 times. Most recent error: FirebaseError: [code=permission-denied]: Permission denied on resource project MY_PROJECT_ID.
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.
My firebase.js code is
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";
import "firebase/compat/storage";
const firebaseConfig = {
apiKey: MY_API_KEY,
authDomain: MY_AUTH_DOMAIN,
projectId: MY_PROJECT_ID,
storageBucket: MY_STORAGE_BUCKET_URL,
messagingSenderId: MY_MESSAGING_SENDER_ID,
appId: MY_APP_IP,
measurementId: MY_MEASUREMENT_ID,
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore();
const auth = firebase.auth();
const provider = new firebase.auth.GoogleAuthProvider();
const storage = firebase.storage();
export { auth, provider, storage };
export default db;
Please help me .

New firebase v(9.1.1) is modular based version. Therefore you have to import everything as named import from respective files.
eg:-
import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'
const firebase = initializeApp({
apiKey: MY_API_KEY,
authDomain: MY_AUTH_DOMAIN,
projectId: MY_PROJECT_ID,
storageBucket: MY_STORAGE_BUCKET_URL,
messagingSenderId: MY_MESSAGING_SENDER_ID,
appId: MY_APP_IP,
measurementId: MY_MEASUREMENT_ID,
})
const firestore = getFirestore()
The method/function way of using firebase is not supported in v(9.1.1), this probably helps with tree shaking(loading only required files/functions, rather than entire library), which saves loading time and creates fast user experience.
For detailed information checkout these videos:-enter link description here
Also check firebase docs:-enter link description here

Can you please try to generate a new firebaseConfig file? You can do that by
Going to your project settings.
At the bottom of the page there's a section called Your apps.
On the top right of that section click the button labeled Add App.
Choose the icon for webapp (3rd from the left).
After choosing a name for the new webapp, you'll get your new fbconfig.
Copy new fbconfig to your project and try again.
Let me know what happens please.
EDIT 0 -

Related

Getting an unusual error using firebase with react native

I am trying to link up firebase to my app so that i can store my habits on a database rather than just have them locally. I have looked up a ton of documentation and downloaded countless firebase packages to try and figure out how to connect my firebase app, but i am still running into a lot of problems.
the error reads:
While trying to resolve module idb from file /Users/jonnywerthman/Desktop/Dev stuff/personal/90dayz/90DayZ/node_modules/#firebase/app/dist/esm/index.esm2017.js, the package /Users/jonnywerthman/Desktop/Dev stuff/personal/90dayz/90DayZ/node_modules/idb/package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (/Users/jonnywerthman/Desktop/Dev stuff/personal/90dayz/90DayZ/node_modules/idb/build/index.cjs. Indeed, none of these files exist:
here is what my config file looks like:
import * as firebase from 'firebase/compat/app'
import 'firebase/compat/firestore'
import 'firebase/compat/auth'
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
};
// Initialize Firebase
if (firebase.apps.length === 0){
const firebaseApp = firebase.initializeApp(firebaseConfig)
} else {
app = firebase.app()
}
const db = app.firestore();
const auth = firebase.auth();
export default {db, auth}
My guess is that either I don't have something downloaded that I should, or I messed up the .env file somehow
You need use https://rnfirebase.io/database/usage for React Native projects

Unable to connect React Native app to Firestore emulator

I've tried just about EVERY solution on Stack Overflow and beyond, and still getting errors.
I've setup and confirmed the emulator runs fine. However, trying to connect the react native app to it returns the error:
Could not reach Cloud Firestore backend. Connection failed 1 times...
followed by a bunch of these warnings:
Connnection Webchannel transport errored .
Here's my config info
import * as firebase from 'firebase';
import { initializeApp } from "firebase/app";
import firestore from 'firebase/firestore';
const firebaseConfig = {
apiKey: "ZZZZ",
authDomain: "ZZZZ",
projectId: "ZZZZ",
storageBucket: "ZZZZ",
messagingSenderId: "ZZZZ",
appId: "ZZZ",
measurementId: "ZZZ"
};
firebase.initializeApp(firebaseConfig);
firebase.firestore().useEmulator("localhost", 8080);
I even replaced localhost with 0.0.0.0, same error.
Someone recommended changing the last line to
firebase.firestore().settings({
host: "localhost:8080",
ssl: false
});
which I tried, but still got the same errors.
Please what's the correct, VERIFIED way of doing this? I'd really appreciate it 'cos I want to spend hours on this!
I’m afraid you are not correctly importing firestore and neither initializing the emulator in the appropriate way. You are importing the Firebase function correctly, but there are a few things you need to change.
I will reference Firebase version 9 since it is the one that should be used, if you would like to still use version 8, I will leave the references where you can choose which version to use.
Instrument your app to talk to the emulators
Set up your in-app configuration or test classes to interact with Cloud Firestore as follows.
import { `getFirestore`, connectFirestoreEmulator } from "firebase/firestore";
// firebaseApps previously initialized using initializeApp()
const db = getFirestore();
connectFirestoreEmulator(db, 'localhost', 8080);
When you initialize Firebase you need to do it this way after installing firebase using npm.
const app = initializeApp(firebaseConfig);
and...
Initialize Cloud Firestore
Initialize an instance of Cloud Firestore:
import { initializeApp } from "firebase/app"
import { getFirestore } from "firebase/firestore"
const firebaseApp = initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
const db = getFirestore();
At the end your file should look like this:
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore';
import { getFirestore, connectFirestoreEmulator } from "firebase/firestore";
const firebaseConfig = {
apiKey: "ZZZZ",
authDomain: "ZZZZ",
projectId: "ZZZZ",
storageBucket: "ZZZZ",
messagingSenderId: "ZZZZ",
appId: "ZZZ",
measurementId: "ZZZ"
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
connectFirestoreEmulator(db, 'localhost', 8080);

firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.database is not a function

I'm getting the error below when trying to connect my app with Firebase:
firebase_compat_app__WEBPACK_IMPORTED_MODULE_0__.default.database is not a function
I also did a test and I see that it happening only when connecting the database. If I comment on the database line, it works.
I also tried changing the rules on Firebase to true, and still not working.
Note: I'm trying to use realtime database
Here is my code:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY ,
authDomain: process.env.REACT_APP_AUTH_DOMAIN ,
databaseURL: process.env.REACT_APP_DATABASE_URL,
projectId: process.env.REACT_APP_PROJECT_ID,
storageBucket: process.env.REACT_APP_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_APP_ID
};
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const database = firebase.database();
export{ firebase, auth, database}
Firebase has two databases:
Firestore
Realtime Database
While they're both part of Firebase, they're completely separate.
You're importing firebase/compat/firestore, so Firestore. But then you call firebase.database(), which is the Realtime Database.
You'll need to pick one and stick with it:
If you want to use Firestore, keep your import as is and access it with firebase.firestore().
If you want to use Realtime Database, keep the call as is but import firebase/compat/database.

Firebase and reactjs: Firebase App named '[DEFAULT]' already exists (app/duplicate-app) [duplicate]

I started a project and occurred an error when importing firebase in more than one component.
In this firebase start file:
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "fdsfsdfdsf",
authDomain: "fdsfdsfsdfdsf",
databaseURL: "sdfdsfdsf",
projectId: "dsfdsfdsf",
storageBucket: "dsfdsfdsf",
messagingSenderId: "dsfdsfsdfdsf"
}
const FbApp = firebase.initializeApp(firebaseConfig)
export default FbApp.auth()
Then in the components:
import firebase from '../lib/firebaseClient'
With a single component works well, but if I add a new component with:
import firebase from '../lib/firebaseClient'
The application fail:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
I had same issue, then I found out this:
if (!firebase.apps.length) {
firebase.initializeApp({});
}
https://github.com/zeit/next.js/issues/1999
The solution:
import firebase from 'firebase'
try {
firebase.initializeApp({
databaseURL: 'dfgdfg'
})
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
const auth = firebase.auth()
export default auth
My understanding is that the error is due to calling initializeApp() more than once for your database. Scan through your code to make sure you only call initializeApp() once. For me, this included checking any js files that might be calling the method and checking for duplicate js files in your html file.
I recently solved this error in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
On serverside something like this should work
const admin = require('firebase-admin');
const serviceAccount = require('./../../credentials/server');
// Check if firebase already been initialized
if (!admin.apps.length) {
// Initialize Firestore.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
Summarizing all good answers.
A better fix would be to load environment variables from .env.local into process.env.
//.env.local
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
Next up, we can initialize the Firebase SDK on the client-side like this.
//shared/configs/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const clientCredentials = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
if (!firebase.apps.length) {
firebase.initializeApp(clientCredentials);
}
export default firebase;
Finally, import the Firebase deps to other file.
//pages/index.js
import firebase from '../shared/configs/firebase';
So I ran into this issue because of some aspect of Next's hot reloading. I was using code like the following to ensure that I didn't call initializeApp more than once:
export let adminClient;
adminClient = adminClient || admin.initializeApp({...});
This didn't work because it seemed like the hot reloading was clearing adminClient, so I kept trying to call initializeApp, even though firebase still had the app recorded as being initialized.
To fix this, I used the following snippet:
const getAppInstance = () => {
if (admin.apps.length) {
return admin.apps[0];
} else {
return initApp();
}
}
export const adminClient = getAppInstance();
which works on a fresh server start, or when hot reloading due to code changes in development.
If you are using a new Modular SDK v9.0.1 then it might not support the "firebase" namespace.
The Implementation, I used
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
//App configure
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
if (!getApps().length) {
console.log(`...`)
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
export default app
Reference:
StackOverflow: Visit
Firebase Docs: Visit
Firebase Tutorial Setup: Visit

React NextJS Firebase error refresh Firebase App named '[DEFAULT]' already exists

I started a project and occurred an error when importing firebase in more than one component.
In this firebase start file:
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "fdsfsdfdsf",
authDomain: "fdsfdsfsdfdsf",
databaseURL: "sdfdsfdsf",
projectId: "dsfdsfdsf",
storageBucket: "dsfdsfdsf",
messagingSenderId: "dsfdsfsdfdsf"
}
const FbApp = firebase.initializeApp(firebaseConfig)
export default FbApp.auth()
Then in the components:
import firebase from '../lib/firebaseClient'
With a single component works well, but if I add a new component with:
import firebase from '../lib/firebaseClient'
The application fail:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
I had same issue, then I found out this:
if (!firebase.apps.length) {
firebase.initializeApp({});
}
https://github.com/zeit/next.js/issues/1999
The solution:
import firebase from 'firebase'
try {
firebase.initializeApp({
databaseURL: 'dfgdfg'
})
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
const auth = firebase.auth()
export default auth
My understanding is that the error is due to calling initializeApp() more than once for your database. Scan through your code to make sure you only call initializeApp() once. For me, this included checking any js files that might be calling the method and checking for duplicate js files in your html file.
I recently solved this error in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
On serverside something like this should work
const admin = require('firebase-admin');
const serviceAccount = require('./../../credentials/server');
// Check if firebase already been initialized
if (!admin.apps.length) {
// Initialize Firestore.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
Summarizing all good answers.
A better fix would be to load environment variables from .env.local into process.env.
//.env.local
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
Next up, we can initialize the Firebase SDK on the client-side like this.
//shared/configs/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
const clientCredentials = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};
if (!firebase.apps.length) {
firebase.initializeApp(clientCredentials);
}
export default firebase;
Finally, import the Firebase deps to other file.
//pages/index.js
import firebase from '../shared/configs/firebase';
So I ran into this issue because of some aspect of Next's hot reloading. I was using code like the following to ensure that I didn't call initializeApp more than once:
export let adminClient;
adminClient = adminClient || admin.initializeApp({...});
This didn't work because it seemed like the hot reloading was clearing adminClient, so I kept trying to call initializeApp, even though firebase still had the app recorded as being initialized.
To fix this, I used the following snippet:
const getAppInstance = () => {
if (admin.apps.length) {
return admin.apps[0];
} else {
return initApp();
}
}
export const adminClient = getAppInstance();
which works on a fresh server start, or when hot reloading due to code changes in development.
If you are using a new Modular SDK v9.0.1 then it might not support the "firebase" namespace.
The Implementation, I used
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
//App configure
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
if (!getApps().length) {
console.log(`...`)
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
export default app
Reference:
StackOverflow: Visit
Firebase Docs: Visit
Firebase Tutorial Setup: Visit

Resources