Environment Variables in React Native - Kevin Uriel Fonseca


Create a file with the name of app.config.js inside the root directory of your project and paste the following code:

const myAppName = 'Song Finder'export default () => {  if (process.env.NODE_ENV === 'development') {    return {      name: myAppName,      version: '1.0.0',      // All values in extra will be passed to your app.      extra: {        API_URL: 'http://localhost:5000/api/v1',      },    }  } else {    return {      name: myAppName,      version: '1.0.0',      // All values in extra will be passed to your app.      extra: {        API_URL: 'https://YOUR_PUBLIC_API_URL/api/v1',      },    }  }}

Furthermore, you will need to initiate your app with the command of npx cross-env NODE_END=development expo start/public. You might be prompted to install cross-env, please do!

Moreover, you will also need to install a npm library called expo-contants, npm i expo-constants. This library will make the environment variables available accross your app.

import Constants from "expo-constants";import { View, Text } from "react-native";const Playlists = () => {    return (    <View>    	<Text>{JSON.stringify(Constants.manifest.extra.API_URL, null, 4)}</Text>    </View>  )}export default Playlists.

Lastly, React Native does not really lets you connect to your localhost server. However, there’s a solution that it is easy to implement. Open your CMD in your Windows machine and type the following command, ipconfig then simply scrolldown to the Wireless LAN adapter Wi-Fi and copy the address under the IPv4 Address section. It should look like this:

Wireless LAN adapter Wi-Fi:   Connection-specific DNS Suffix  . : attlocal.net   IPv6 Address. . . . . . . . . . . : XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX   Temporary IPv6 Address. . . . . . : XXXX:XXXX:XXXXX:XXXX:XXXX:XXXX:XXXX:XXXX   Link-local IPv6 Address . . . . . : XXXX::XXXX:XXXX:XXXX:XXXX%X   IPv4 Address. . . . . . . . . . . : 192.168.1.73   Subnet Mask . . . . . . . . . . . : XXX.XXX.XXX.X   Default Gateway . . . . . . . . . : XXXX::XXXX:XXXX:XXXX:XXXX%X                                       XXX.XXX.X.XXX

NOTE: When running the command to initiate your app, plase make sure to use either start or publish, NOT BOTH!

Bye Bye 🙂

SIDEBAR
FOOTER