Could not reach Cloud Firestore backend - React native Firebase v9
A

5

14

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:

  1. Changing the firestore database rules as mentioned in this answer: https://mcmap.net/q/827042/-firestore-could-not-reach-cloud-firestore-backend-error-when-starting-react-native-application-with-react-native-run-android-command

  2. Using this workaround: https://github.com/firebase/firebase-js-sdk/issues/5667#issuecomment-952079600

  3. I'm not using any .env variables according to this answer: https://mcmap.net/q/827043/-firebase-9-0-0-8-beta-could-not-reach-cloud-firestore-backend-backend-didn-39-t-respond-within-10-seconds

  4. Wiped android emulator data, then Cold Boot. Didn't work.

  5. Upgraded firebase-9.6.3 to firebase-9.6.6. Didn't work.

  6. 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.
Acinaciform answered 9/2, 2022 at 7:43 Comment(3)
Can you edit it and add a the code where you are calling firebase? That is just the initializationStarshaped
@Starshaped added.Acinaciform
@Starshaped Hi, what happened? Do you need something else for solving this issue? I'm really struggling here.Acinaciform
A
42

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!

Acinaciform answered 10/2, 2022 at 6:51 Comment(3)
Tried this but getting a strange error. FirebaseError: initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.Determinant
@KyleJ try to restart the server, it helped me.Ninnetta
I think my solution on a Windows 11 computer was to allow my web browser to have access to both private and home networks (all ports). I restored my firewall settings, and allowed these two options when my web browser (Google Chrome) asked for it again after the restoration - there are probably other ways of doing this. But everything "magically" worked after that for me. I did have a local connection problem, which was my browser it appears.Blackface
C
4

This thing happened to me also. I had many solutions on the internet and all of the 6 as well. Noting helped. I was using donenv file in my firestore config then I get rid of donenv and write the variables as hard-coded then it started to work.

Coz answered 18/3, 2023 at 0:3 Comment(0)
M
2

Edited version for 2023: I asked chat GPT and this format worked. Restart your server after these changes

import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import "firebase/compat/firestore";

const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
}

const db = firebase.firestore();
const settings = { timestampsInSnapshots: true };
db.settings(settings);

// Enable experimentalForceLongPolling for Firestore
const firestoreConfig = {
  experimentalForceLongPolling: true,
};
const firestore = firebase.firestore(firebase.app());
firestore.settings(firestoreConfig);

export { firebase, db };
Mete answered 16/4, 2023 at 4:12 Comment(0)
L
1

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

Lagoon answered 17/1, 2023 at 5:46 Comment(0)
C
0

I was encountering the same error but the problem was with my internet connection was too slow too load the firebase data to the react native frontend.

Cyr answered 7/6, 2024 at 5:46 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.