While working on a mobile app using React Native and Expo, I ran into an issue where I was unable to connect to a local instance of Supabase from my Android Emulator.
My local Supabase instance was running at: http://127.0.0.1:54321.
When initializing the Supabase JavaScript client, I was simply passing in this URL and anon key:
const supabase = createClient<Database>(supabaseUrl, supabaseAnonKey)
While this worked fine on iOS Simulator, on Android Emulators, I would keep getting an error:
TypeError: Network request failed
Per the official Android documentation, the reason why is because Android Emulators sit behind their own virtual router, so the virtual devices can't see the host computer. They only see a router connection. That router gives the emulator an IP in the 10.0.2.x range, keeping all traffic inside this private network.
The fix is to use a special alias IP that points to the host computer's own local address (127.0.0.1). Per the Android docs, this alias IP is:
10.0.2.2
Changing the URL to http://10.0.2.2:54321 fixed the issue on Android, but caused iOS to break with the same error: TypeError: Network request failed.
To fix the issue for both platforms, I used the Platform helper from react-native to conditionally select the correct URL:
export const supabaseUrl = Platform.select({
ios: http://127.0.0.1:54321,
android: http://10.0.2.2:54321,
});