You may have your own API of which you need to connect your React Native app to. Naturally you’d like to test this locally in development rather than in production on the server. With Xcode this is easier as it uses a simulator, whereas Android Studio uses an emulator which makes it much more challenging to connect to localhost. Developing/testing on a physical device is a more desirable solution for me also as it means Android Studio doesn’t chew up all of my RAM.

I tried multiple Stackoverflow solutions but found that when your development API uses a subdomain (ie api.localhost:5000) the api won’t get picked up as a subdomain. We can’t use an alias either (ie myapi.com) because the Android device doesn’t have the alias to point it to the loopback address. This is only possible on rooted phones after you modify the android /etc/hosts file as described here.

A good way around this is to use ngrok which you can install with homebrew. Then in the terminal run:

ngrok http -region=au -host-header=rewrite api.lvh.me:3000

I use my region (au) for speedier results, and ngrok needs to point to the subdomain for my api. This has been set up by adding 127.0.0.1 api.lvh.me to my hosts file

In your React Native code you can now use ngrok to access your localhost API, ie:

if (__DEV__)
  return 'https://your_random_address.au.ngrok.io'

Posts