Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variables not work in React Native - Expo

Hi guys i try for create global variables with file .env but not works i use react native expo i wrote process.env.API_URL but not found this variable. What i to do for works ?

I'm desesperated

I read https://www.npmjs.com/package/react-native-dotenv and https://docs.expo.io/guides/environment-variables/ but not works for me. I need HELP !!!

like image 608
ardoYep Avatar asked Jan 20 '26 20:01

ardoYep


1 Answers

I ran into so many issues getting environment variables to work. Oddly, the most highly recommended package was react-native-dotenv, and the first line of code in index.js is to require('fs'), which is a Node module that isn't available in React Native.

Anyways, I ended up creating a new context to handle Environment Variables. I don't have logic to automatically import variables based on environment, but that's as simple as commenting out one line.

Create a JSON file with your variables, import it into your context, and place it at the top of your app.js return, allowing everything in your app to consume it. From there, import it with useContext() as you would any other context, and you have access to all your variables.

Edit: After repeated issues, I decided to simply only use production variables for app testing. It's not ideal at all, but I'm sure many are in the same position as I'm in where the only real difference in variables is the route name for the API (local test server vs. production server). Unfortunately, both iOS and Android do not support http requests, or https requests with self-signed certificates without editing config files. Those config files are not available if you're using an Expo managed flow. Thus, my only choice was to simply do my testing on the production API. Luckily, I have good logs to go by, and the API itself is fairly mature and has endured plenty of testing via the web React app.

If anyone has a better solution, I'd love to hear it.

like image 134
Logic.Analyzer Avatar answered Jan 23 '26 11:01

Logic.Analyzer