React Native: .env file values aren't being read with react-native-config

1.4k views Asked by At

I'm rebuilding my Expo app in pure React Native and trying to figure out the environment variable situation. I'm trying out react-native-config, currently on "^1.5.1". I installed using yarn add react-native-config and then I did npx pod-install.

Here is my .env file:

ENV_NAME=prod
TEST_ENV_VAR=hello

And for one of my components, I have code like this:

import Config from "react-native-config";

export function LoginScreen({ navigation }) {
   ...
   const [isDev, setIsDev] = React.useState(Config.ENV_NAME === 'dev')
   const [testEnvString, setTestEnvString] = useState(Config.TEST_ENV_VAR)
   ...

   return (
      ...
        {isDev ? 
        <View style={styles.row}>
            <Text>Debug info: {isDev}</Text>
            <Text>Test string: {testEnvString}</Text>
        </View>
        : null}
      ...
   )

What I'm finding is that:

  • isDev always evaluates to true, ie that snippet in the return ( ) is always showing, even when the .env file has ENV_NAME=prod
  • isDev does not itself show up as a value after the string "Debug info: " - so it's some kind of value that shows up as blank but evaluates to true
  • testEnvString also does not show up in the displayed component

Am I missing anything in my setup here?

Addendum: I'm testing on iOS simulator (I don't care about Android yet) with npm start

2

There are 2 answers

0
Fanchen Bao On

Try cleaning your iOS build and then rebuilding. From my experience, .env or change to .env is not loaded until the project is completely rebuilt from scratch.

react-native-clean-project is a handy tool to perform the cleaning task. Follow the instruction to install, run npm run clean, and answer yes only to "Wipe iOS build folder". Once the cleaning is done, rebuild the app and you shall see the values .env.

One caveat of using react-native-clean-project is that it favors interactive prompt. There are non-interactive flags, but they are quite lacking. Thus, if you want to do the cleaning non-interactively, run the following command (copied from here):

rm -rf ios/build && (killall Xcode || true) && xcrun -k && cd ios && xcodebuild -alltargets clean && cd .. && rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang/ModuleCache" && rm -rf "$(getconf DARWIN_USER_CACHE_DIR)/org.llvm.clang.$(whoami)/ModuleCache" && rm -fr ~/Library/Developer/Xcode/DerivedData/ && rm -fr ~/Library/Caches/com.apple.dt.Xcode/
2
kenmistry On

I see that you are using Expo so its docs mention about the use of the process.env.EXPO_PUBLIC_[VARNAME] reference here if you are going to display the environment variables publicly.