Why your React Native app can't connect to your local .NET API (And how to fix it)
Source: Dev.to
The Problem: What is “Localhost”?
When you type localhost inside your React Native code, the code is running on the mobile device (or emulator).
- On your computer,
localhostrefers to the computer itself. - On an Android emulator,
localhostrefers to the Android device’s internal loopback network.
The emulator looks inside itself for a .NET server that doesn’t exist, resulting in a Network Error.
The Solution: The Magic IP Addresses
Testing on the iOS Simulator (Mac)
Apple’s iOS simulator shares the host machine’s network.
URL to use: http://localhost:/api/...
Testing on the Android Emulator
Android emulators run on an isolated virtual router. Google provides a special alias IP to reach the host machine.
URL to use: http://10.0.2.2:/api/...
Testing on a Physical Device (iPhone or Android via Wi‑Fi)
On a real phone, neither localhost nor 10.0.2.2 works. Use your computer’s local Wi‑Fi IP address.
- Open a terminal and run
ipconfig(Windows) orifconfig(macOS). - Find your IPv4 address (e.g.,
192.168.1.Xor10.0.0.X).
URL to use: http://192.168.1.X:/api/...
Note: Ensure your .NET API listens on all interfaces, not just
localhost.
Example:dotnet run --urls "http://0.0.0.0:"
The Best Practice: Environment Configuration
Instead of manually changing Axios URLs for each platform, configure a dynamic environment variable.
.env file (Expo)
# Change this depending on your testing device!
# iOS Simulator
# EXPO_PUBLIC_API_URL=http://localhost:5257/api
# Android Emulator
EXPO_PUBLIC_API_URL=http://10.0.2.2:5257/api
# Physical Device
# EXPO_PUBLIC_API_URL=http://192.168.1.45:5257/apiAxios instance (TypeScript)
import axios from 'axios';
const api = axios.create({
baseURL: process.env.EXPO_PUBLIC_API_URL,
headers: {
'Content-Type': 'application/json',
},
});
export default api;Now you only need to uncomment the appropriate line in .env, restart the Expo server with npx expo start -c (to clear the cache), and the API will connect correctly across all devices.