Search code examples
react-nativeenvironment-variableslocalexpo

React Native with Expo: how to use a .env.local config file?


I have a react-native app running with expo (expo 27.1.1 and react-native 0.55.4).

I'd like to use a .env.local file, the only thing I found is using babel-plugin-inline-dotenv, but it loads the content of .env file instead of .env.local file (and I want it to load the content of .env.local if the file exists otherwise .env).

Is there an other similar plugin allowing that?


Solution

  • I finally found a solution:

    Add a file env.js with this:

    import Constants from "expo-constants";
    
    function getEnvVars() {
      if (__DEV__) {
        return returnEnvVars();
      } else {
          return new Promise(resolve => {
              resolve(Constants.manifest.extra);
          });
      }
    }
    
    async function returnEnvVars() {
      return await import("envLocal.js");
    }
    
    export default getEnvVars;
    

    Then you can put your env variables in the file envLocal.js like this:

    export default {
      test: "localhost"
    };
    

    and your prod variables in your app.json file, like this:

    {
      "expo": {
        "extra": {
          "test": "prod"
       }
    }
    

    Finally you can call it like this:

    import getEnvVars from "../environment";
    getEnvVars().then(vars => console.log(vars));