Trouble Connecting Expo React Native App to Local Express Server on Android Emulator

I’m stuck trying to get my Expo React Native app to talk to my local Express server when using the Android emulator. It’s driving me nuts!

Here’s what’s going on:

  • The app works fine on the web version (using expo start --web)
  • But when I fire up the Android emulator, it’s like the frontend and backend are in different galaxies

I’ve tried a bunch of stuff:

  • Messed with the API_URL in my .env.development file
  • Updated app.json to allow cleartext traffic
  • Double-checked that my backend is actually running
  • Even tested the API URL in Postman (it works there!)

My .env.development file looks like this:

API_URL=http://10.0.2.2:3000

And here’s a snippet from my frontend code:

export const login = async (email, password) => {
  console.log('API_URL', API_URL);
  const response = await fetch(`${API_URL}/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ email, password }),
  });
  const data = await response.json();
  if (!response.ok) throw new Error(data.error);
  return data;
};

Any ideas what I’m missing? This is making me pull my hair out!

I’ve encountered this issue before, and it can be frustrating. One thing to check is your Android emulator’s network settings. Sometimes, the emulator doesn’t automatically connect to the host machine’s network.

Try this: in your Android emulator, go to Settings > Network & Internet > Wi-Fi. Make sure it’s connected to a network. If not, you might need to set up a virtual router in Android Studio.

Another potential solution is to use the actual IP address of your computer instead of 10.0.2.2. You can find this by running ‘ipconfig’ (Windows) or ‘ifconfig’ (Mac/Linux) in your terminal.

Lastly, ensure your Express server is configured to accept connections from all IP addresses. In your server code, try binding to ‘0.0.0.0’ instead of ‘localhost’ or ‘127.0.0.1’.

Hope this helps! Let me know if you need more clarification on any of these steps.

hey iris72, have u tried using ngrok? it’s a nifty tool that creates a secure tunnel to ur local server. might solve ur connection headache! plus, it gives u a public URL to test on real devices. what do u think? ever used it before?

yo, have u tried using ‘localhost’ instead of the IP? sometimes that works better. also, check ur firewall settings - they might be blocking the connection. if nothing else works, try restarting both the emulator and ur express server. good luck man!