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
-
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
-
Updated
app.json
to allow cleartext traffic:"expo": { "android": { "usesCleartextTraffic": true } }
-
Confirmed backend is running:
- Accessing http://localhost:3000 in my browser works fine.
Disabled firewall/antivirus to ensure they aren’t blocking requests.
- Accessing http://localhost:3000 in my browser works fine.
-
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
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?.env.development
should start byEXPO_PUBLIC_
, so in your caseEXPO_PUBLIC_API_URL
Environment variables in Expo
http://192.168.x.x:3000