5

I try to build an eCommerce app with Expo and react native but I face a network error, the google service is active on the device (simulator for android and real iPhone for IOS) and I'm connected to my Google account.

I also try to prevent the page to reload but nothing changed. After some research, all I see is I'm not the only one to face this error I don't find any valuable answer so I'm ending up here.

here my code:

const LoginScreen = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isSignedIn, setIsSignedIn] = useState(false);

  const handleCreateAccount = (e) => {
    e.preventDefault();
    createUserWithEmailAndPassword(authentification, email, password)
      .then((userCredential) => {
        console.log(userCredential);
      })
      .catch((error) => {
        console.log(error.message);
      });
  };

  const handleSignIn = (e) => {
    e.preventDefault();
    signWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        console.log("Signed in!");
        const user = userCredential.user;
        console.log(user);
      })
      .catch((error) => {
        console.log(error);
        Alert.alert(error.message);
      });
  };

      <ScrollView
        contentContainerStyle={{
          flex: 1,
          width: "100%",
          height: "100%",
          alignItems: "center",
          justifyContent: "center",
        }}
      >
        <BlurView intensity={100}>
          <View style={styles.login}>
            <Image
              source={{ uri: profilePicture }}
              style={styles.profilePicture}
            />
            <Text style={{ fontSize: 17, fontWeight: "400", color: "white" }}>
              email
            </Text>
            <TextInput
              onChangeText={(text) => setEmail(text)}
              style={styles.input}
              placeholder="[email protected]"
              keyboardType="email-address"
              textContentType="emailAddress"
            />
            <Text style={{ fontSize: 17, fontWeight: "400", color: "white" }}>
              mot de passe
            </Text>
            <TextInput
              onChange={(text) => setPassword(text)}
              style={styles.input}
              placeholder="your password"
              secureTextEntry={true}
            />
            <Button
              onPress={handleSignIn}
              title="Connexion"
              buttonStyle={{
                width: 250,
                height: 40,
                borderRadius: 10,
                backgroundColor: "#00CFEB90",
                alignItems: "center",
                justifyContent: "center",
                marginVertical: 10,
                borderColor: "#fff",
                borderWidth: 2,
              }}
              type="outline"
              titleStyle={{ color: "white", fontSize: 17 }}
            />
            <Button
              onPress={handleCreateAccount}
              title="Créer un compte"
              buttonStyle={{
                width: 250,
                height: 40,
                borderRadius: 10,
                backgroundColor: "#6792F090",
                alignItems: "center",
                justifyContent: "center",
                marginVertical: 10,
                borderColor: "#fff",
                borderWidth: 2,
              }}
              type="outline"
              titleStyle={{ color: "white", fontSize: 17 }}
            />
          </View>
        </BlurView>
      </ScrollView>

So I need help.

2
  • I have the same problem with the web version, however, only on iOS devices. It works with other devices. Commented Jan 31, 2022 at 16:37
  • i think is the code for the form/text input cause i try the same function in another project with a different type of form and it's work on android simulator and the Iphone. Commented Jan 31, 2022 at 17:02

10 Answers 10

14

In case it helps someone. I had the same issue and lost many hours investigating. It turned out that in my case, it was simply a DNS issue in the firebase layer. localhost in the URL of the emulator was not resolved. I replaced it with 127.0.0.1 and it is working fine.

Sign up to request clarification or add additional context in comments.

2 Comments

After two days of debugging... This has saved me. Thanks a lot!
how i can do this i do not understand
6

The auth/network-request-failed error can be especially misleading as it seems to arise for a bunch of different reasons. I've seen it for any of the following:

  1. Wrong Version of the SDK - To use auth on native devices, you need to use the native SDK, not the JavaScript SDK. Some other Firebase features may work via the JS SDK, but auth won't as it has extra security layers. Make sure you're using the correct version.
  2. Emulator Issues - Your emulator can't access the internet or has stale DNS or an incorrect system time. Check and make sure your device has internet access, the clock on the device is set correctly, and that the DNS for your project resolves. For DNS you can try switching to Google's DNS (8.8.8.8) or Cloudflare's (1.1.1.1) and see if either of those help.
  3. No Google Play Services - On Android, auth requires Google Play services be installed on the device emulator. See here for details.
  4. Incorrect Firebase Setup - Make sure you've followed every item in the Getting Started instructions from both Expo and React Native Firebase, in particular the credentials portions and making sure that the package names match on Android and Bundle IDs match on iOS.

If none of the above work, provide the full error your getting (check both the React errors and the device-level error logs).

4 Comments

this is driving me batty, I've checked everything 10 times :( stackoverflow.com/questions/72042995/…
An old one, but im struggling with this. In your first bullet, what is "native SDK"? Expo documents say you can use JS sdk for firebase auth.
@Fahad - If you're trying to use Firebase auth in an iPhone or Android app, you'll need to use the native SDKs for those platforms. IIRC, most of the other features will work if you use the JS SDK, but auth specifically will not.
if using emulators do I still need internet??
6

I was getting this error on an ios simulator and the solution for me was to flash the dns on my mac by running sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

Hope this helps someone

1 Comment

This solved my problem, thanks! I had changed the port of the UI and the Auth emulator was not connecting correctly. Getting: firebase [ Failed to connect to /127.0.0.1:9099 ] Stopped everything, run the command to clear the DNS and restarted again.
3

This helped for error: auth/network-request-failed whilst using the iOS Simulator.

If you followed the documentation and implemented emulation for FirebaseAuth in debug mode. https://firebase.google.com/docs/emulator-suite/

Setup the emulator then run:

firebase emulators:start

I should work after that and you can manage users at http://localhost:4000/auth.

Comments

1

In my case the problem was with the way the emulator's address and port were specified.

I had

connectAuthEmulator(auth, "http://127.0.0.1", "9099");

Now I have

connectAuthEmulator(auth, "http://127.0.0.1:9099");

and it works.

Comments

1

In case this helps someone who is seeing this error in a Firefox (maybe other browsers) and you have a browser update pending.

First if you have an update pending of the browser make sure to accept it, the browser will limit some operations if the update is pending. Try your app again after your browser reloads.

In this case it seems that it cannot properly write/read from Index Db for firebase-heartbeat-store. You can look in the Debugger --> Storage --> Index Db to find this value. Example data [DEFAULT]!1:23456:web:78910:Object. The problem for the emulator is that heartbeatService.ts is throwing an error if for whatever reason Index Db operations are failing.

If this is a case no request at all will be made to emulator for auth (i.e no request to http://127.0.0.1:9099 in the Debugger --> Network tab.

The emulator must be set up and initialized like this

if (isRunningOnLocalhost) {
  const app = initializeApp(firebaseConfig); // get config from firebase console
  const auth = getAuth(app);
  // must call these IMMEDIATELY after initializeApp
  connectAuthEmulator(auth, 'http://127.0.0.1:9099');
}

Comments

1

For people running into this issues in a combination of Expo/Firebase JS SDK Emulators + Android Emulator, we need to use 10.0.2.2 instead of localhost or 127.0.0.1 for the Firebase Auth Emulator url.

E. g.

export const FIREBASE_APP = initializeApp(firebaseConfig)
export const FIREBASE_AUTH = initializeAuth(FIREBASE_APP, {
  persistence: getReactNativePersistence(ReactNativeAsyncStorage),
})
export const FIREBASE_DB = getFirestore(FIREBASE_APP)

if (isRunningOnLocalhost()) {
  const emulatorHost = Platform.OS === 'android' ? '10.0.2.2' : 'localhost'
  connectAuthEmulator(FIREBASE_AUTH, `http://${emulatorHost}:9099`)
  connectFirestoreEmulator(FIREBASE_DB, emulatorHost, 8080)
}

2 Comments

For what it's worth, here's my current firebaseConfig.ts file managing all of this with emulators, etc. Maybe it helps someone: gist.github.com/RobSteward/e853a63ec5d6938783cd03f44959a324
Combined with rankki.xyz/posts/use-firebase-remote-config-with-expo for using remote config.
1

after 2 days of debugging I find out that while it was working fine in simulator it gives auth/network-request-failed error in real iphone device.

after a while I found that the root cause of issue was emulator ip and port.

since we always tend to use emulator auth (or firestore) in 127.0.0.1 and this IP is not reachable from the real iphnoe device as its separate device from Macbook..

here is you can solve it (you will still be able to use emulator)

open your firebase.json file and write down host ip explicitly 0.0.0.0 here is how it looks

  {
  "firestore": {
    "rules": "firestore.rules",
    "indexes": "firestore.indexes.json"
  },
  "emulators": {
    "firestore": {
      "host": "0.0.0.0",
      "port": 8080
    },
    "ui": {
      "enabled": true
    },
    "singleProjectMode": true,
    "auth": {
      "host": "0.0.0.0",
      "port": 9099
    }
  }
}

in this way it will be available all local network devices

now open your terminal and type ipconfig getifaddr en0 to get the IP of comp.

now open your fireBaseConfig.js

and add IP address to emulator connection block

if (process.env.EXPO_PUBLIC_ENVIRONMENT === "development") {
  connectFirestoreEmulator(DB, "192.168.x.x", 8080); // for connecting test emulator
  connectAuthEmulator(auth, "http://192.168.x.x:9099");
}

Comments

0

Emulator runs on localhost (127.0.0.1), which only allows access from the same device (Web and simulator). But actual mobile devices on the same network cannot reach localhost of the computer running the emulator.

When trying to access Firebase services from a physical phone or another device on the same Wi-Fi, requests fail because:

localhost (127.0.0.1) only refers to the device itself, not the network.
The mobile device cannot reach the emulator running on your computer.
Firebase Emulator needs to listen on an actual network IP, not just localhost

To allow your phone or other devices to connect to the emulator, update firebase.json to use the computer’s actual network IP address.

  1. Find Your Computer's IP Address on Your Local Network (Computer running emulator)
  2. Update firebase.json to Use the IP Address

Modify firebase.json to replace localhost with your actual IP:

{
    "functions": {
    "source": "cloud/functions",
    "predeploy": ["npm --prefix \"$RESOURCE_DIR\" run build"]
    },
    
    "emulators": {
    "functions": {
    "port": 5001
    },
    
    "firestore": {
    "host": "192.168.1.128", //computer ipaddress runing the emulator
    "port": 8080
    },
    
    "ui": {
    "enabled": true
    },
    
    "singleProjectMode": true,
    "auth": {
    "host": "192.168.1.128", //computer ipaddress runing the emulator
    "port": 9099
    }
}

  1. Restart your emulator firebase emulators:start --inspect-functions

You will get this

Authentication │ 192.168.1.128:9099 │ http://127.0.0.1:4000/auth
Firestore │ 192.168.1.128:8080 │ http://127.0.0.1:4000/firestore etc

In your code that switches to emulator

const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const db = getFirestore(app);

if (process.env.FUNCTIONS_EMULATOR) {
    console.log("Connecting Firestore to Emulator...");
    connectFirestoreEmulator(db, "192.168.1.128",8080);
    connectAuthEmulator(auth, "http://192.168.1.128:9099");
}

Comments

0

In my case (I was using React), it was because I was passing references to the email id and password, instead of the values themselves, to the createUserWithEmailAndPassword function.

Changing

createUserWithEmailAndPassword(auth, email, password)

to

createUserWithEmailAndPassword(auth, email.current.value, password.current.value)

solved it for me.

A silly mistake, but the network in the error message deceived me into checking my internet connection and changing localhost to my IP address.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.