skip to Main Content

I’m building a React Native frontend with Expo (managed workflow) and an Express backend running locally. My app works fine on the web version (using expo start --web), but when I test on the Android emulator, the frontend can’t connect to the backend. I’ve tried several things, but nothing seems to work.

What I’ve Tried

  1. Changed the API URL in .env.development:

    • API_URL=http://10.0.2.2:3000 (for Android emulator)
    • API_URL=http://192.xxx.x.x:3000 (my local IP address)
    • API_URL=http://localhost:3000
  2. Updated app.json to allow cleartext traffic:

    "expo": {
      "android": {
        "usesCleartextTraffic": true
      }
    }
    
    
  3. Confirmed backend is running:

    • Accessing http://localhost:3000 in my browser works fine.
      Disabled firewall/antivirus to ensure they aren’t blocking requests.
  4. Tested API URL in Postman using my local IP, and it works.

Relevant code for reference:

.env.development:

#API_URL for web
#API_URL=http://localhost:3000

#API_URL for android
API_URL=http://10.0.2.2:3000

Example frontend api call:

auth.ts:

export const login = async (email: string, password: string) => {
  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;
};

I have a basic cors policy that should not effect this I do not think:

// CORS configuration to allow requests from the frontend
const corsOptions = {
  origin: true,
  credentials: true, // Allow credentials (cookies, headers)
};

app.use(cors(corsOptions));

// Handle preflight requests for all routes
app.options('*', cors(corsOptions));

Please let me know if other information is needed.

2

Answers


  1. In one of Simon’s videos, he says changing the url to http://10.0.2.2:<port> fixes the problem. Could you be overlooking something?

    Login or Signup to reply.
    1. Your environment variables within your .env.development should start by EXPO_PUBLIC_, so in your case EXPO_PUBLIC_API_URL

    The Expo CLI will automatically load environment variables with an EXPO_PUBLIC_ prefix from .env files for use within your JavaScript code whenever you use the Expo CLI, such as when running npx expo start to start your app in local development mode.

    Environment variables in Expo

    1. (In development) The IP address of your backend should be the IP of your own computer, where it’s being host. So in your case http://192.168.x.x:3000
      • Not the IP of your emulator, nor localhost/127.0.0.1. Because the emulator is like another device itself, it’d try to reach itself this way
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search