Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react-native-config example does not read variables from .env file or .env.prod #170

Closed
nomaannomii opened this issue Oct 11, 2017 · 52 comments

Comments

@nomaannomii
Copy link

nomaannomii commented Oct 11, 2017

Windows 10
Mobile Device Nexus 6P
react-native-cli: 2.0.1
react-native: 0.38.1
SET ENVFILE='.env.prod' && react-native run-android

when i run above line on example application its not reading anything from .env file.

@pedro
Copy link
Contributor

pedro commented Oct 11, 2017

Did you do the Android setup?

https://github.com/luggit/react-native-config#extra-step-for-android

@vdesdoigts
Copy link

vdesdoigts commented Oct 11, 2017

Same problem with ENVFILE=.env.prod cd android && ./gradlew assembleRelease , even with

apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

Working fine with react-native run-android debug mode.

@pedro
Copy link
Contributor

pedro commented Oct 11, 2017

Can you paste the output of react-native run-android?

When it's setup properly you can see it's reading (or failing to read) the env like:

$ react-native run-android
Starting JS server...
Building and installing the app on the device (cd android && ./gradlew installDebug...
Reading env from: .env
...

@vdesdoigts
Copy link

It's fine withreact-native run-android

Building and installing the app on the device (cd android && ./gradlew installDebug)...
Reading env from: .env
...

But when I want to build an apk for release, config.ROOT_URL is undefined, there is my .env.prod

ENV=prod
ROOT_URL=https://playgrounds-app.com

@vdesdoigts
Copy link

No fail spotted 🤔

$ ENVFILE=.env.prod cd android && ./gradlew assembleRelease
Reading env from: .env

@pedro
Copy link
Contributor

pedro commented Oct 11, 2017

Oh! How are you setting it to use .env.prod? What are you calling to build the apk?

@pedro
Copy link
Contributor

pedro commented Oct 11, 2017

ah hmm. Does it work if you export ENVFILE=.env.prod instead of setting it this way?

@vdesdoigts
Copy link

I also have a .env, so Reading env from: .env should work

ENV=prod
ROOT_URL=https://playgrounds-app.com

How I use it in my app :

import Config from 'react-native-config';

const axiosConfig = {
  baseURL: `${Config.API_URL}`,
  responseType: 'json',
  headers: { 'Content-Type': 'application/json' },
};

Logs when I launch my app (signed) : java.lang.IllegalArgumentException: unexpected url: undefined/playgrounds/around_me?latitude=48.85661166666667&longitude=2.3522216666666664&distance=5

@vdesdoigts
Copy link

I also see this :react-native-config:compileReleaseJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.). but I'm not sure it's relevant.

@pedro
Copy link
Contributor

pedro commented Oct 11, 2017

Ah weird, so you see "Reading env from .env" when you call gradlew assembleRelease too?

I never had this issue myself, but wondering if it's because of a custom applicationId/applicationIdSuffix, or Proguard.

Have you checked the advanced setup and troubleshooting sections here?

@pedro
Copy link
Contributor

pedro commented Oct 11, 2017

Maybe clean the build too to be sure: cd android/ && ./gradlew clean

@vdesdoigts
Copy link

I change my applicationId and it works! Don't know exactly why.
I used com.playgrounds.app, it works with com.playgrounds, which was the default id.
Thanks for your time 🙏

@pedro
Copy link
Contributor

pedro commented Oct 11, 2017

Ah, phew!

Surprised this didn't cause a compilation failure in 1st place :| hopefully we can fix this at some point.

But thank you! Closing this for now.

@pedro pedro closed this as completed Oct 11, 2017
@Ayyagaries
Copy link

I am unable to solve this problem. with the provided solutions

@CodeAmend
Copy link

It seems the issue for me I needed to add

new ReactNativeConfigPackage(), in the MainApplication.java

@AndreyPatseiko
Copy link

AndreyPatseiko commented Sep 3, 2018

Have the same problem. I can get environment variable when just run react-native run-android, but if I try build sign apk a just can't get only developer values. ((

@AndreyPatseiko
Copy link

For use this constants you mast exported it. And you can't use other assemble type, only assembleRelease. If you create other build type in build.gradle, simple copy release, this don't work.

"build-staging:android": "export ENVFILE=.env.staging && cd android && ./gradlew assembleRelease",

Please add in documentation section "How install manual" - because I spend many time for run lib, because react-native link doesn't work on me.

@aecc
Copy link

aecc commented Mar 2, 2019

It seems the issue for me I needed to add

new ReactNativeConfigPackage(), in the MainApplication.java

I was days trying to figure out why my react Config variable was always empty. That solved it. This NEEDS to be added to the README!

Also the import is:
import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;

@pradhul
Copy link

pradhul commented Mar 28, 2019

for me I was using build variants and adding BuildConfig to progurad file solved it.

@AdamZaczek
Copy link

I already had new ReactNativeConfigPackage() inside MainApplication.java but I had to put it after all the CodePush related stuff. Hope this helps someone!

@RunnableWeb
Copy link

for react native 0.60.0, I have fixed it adding new ReactNativeConfigPackage() manually like so:

@Override
   protected List<ReactPackage> getPackages() {
     @SuppressWarnings("UnnecessaryLocalVariable")
     List<ReactPackage> packages = new PackageList(this).getPackages();
     // Packages that cannot be autolinked yet can be added manually here, for example:
     // packages.add(new MyReactNativePackage());
     packages.add(new ReactNativeConfigPackage());
     
     return packages;
   }

it seems that react native autolinking feature not implemented in this package yet

@sankar4n
Copy link

When we select APK from app bundle in the deploy option, Gradle runs a task named extractApksForFlavour which breaks this regex: https://github.com/luggit/react-native-config/blob/master/android/dotenv.gradle#L10. So make sure that you choose Default APK option when running on device. Screenshot 2019-07-15 at 5 08 21 PM

@LuizFBrisighello
Copy link

for me I was using build variants and adding BuildConfig to progurad file solved it.

@pradhul Can you explain how you did that?

@bericp1
Copy link

bericp1 commented Aug 14, 2019

For react-native@0.60.5 released yesterday it seems like it's no longer required to manually add the package and in fact when you do you get an error. Autolinking appears to work out of the box now for this package on react-native@^0.60.5.

I installed running the following:

$ yarn add react-native-config
$ cd ios && pod install && cd ../

And then I made the manual updates that the README specifies for Android and iOS:

  1. Adding apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" to android/app/build.gradle
  2. Adding -keep class com.mypackage.BuildConfig { *; } to android/app/proguard-rules.pro
  3. Adding pre-build scripts in XCode to be able to use variables in Info.plist and project build settings.

And everything just... worked. In both iOS and Android.

So I think the only thing that's needed is notes in the README:

If your react-native version is < 0.60.0, follow the linking steps below.
If your react-native version is >= 0.60.0 and < 0.60.5, you still need to follow the linking steps below but you need to additionally manually register the package by editing MainApplication.java to add packages.add(new ReactNativeConfigPackage()); in the getPackages method.
If your react-native version is > 0.60.0 this package will work with the autolinker and you don't need to manually run any command to link the package outside of running pod install in the ios directory per the react-native-community/cli docs.

Note: for any RN version (including autolinking) you still need to perform the "extra steps" described below.

Or something to that effect.

EDIT: I've observed this behaviour for both the current published version and the most recent unpublished version (yarn add react-native-config@"luggit/react-native-config#89a602bf8be3808838403a97afaf915caeec76c2")

@LuizFBrisighello
Copy link

LuizFBrisighello commented Aug 16, 2019

@bericp1 I started using RN 0.60.5 and for simple $env:ENVFILE=".env.mycustomenv"; react-native run-android works fine! But adding productFlavors in that mix fucks me up.
Running $env:ENVFILE=".env.mycustomenv"; react-native run-android --variant=myvariantDebug

I still get:
> Configure project :app Reading env from: .env.mycustomenv

but Config.MY_ENV_VAR always returns undefined
Any ideas?

@conor909
Copy link

@aecc ifg I add import com.lugg.ReactNativeConfig.ReactNativeConfigPackage;

and then add new ReactNativeConfigPackage()

I get error: package com.lugg.ReactNativeConfig does not exist

Am I missing an install step?

@waqaramjad
Copy link

i tried all but nothing resolve my issue , still get undefine

@waqaramjad
Copy link

ly

can you give some example that where we run that command because export give error , or may be some other things

@kevinnath1007
Copy link

I change my applicationId and it works! Don't know exactly why.
I used com.playgrounds.app, it works with com.playgrounds, which was the default id.
Thanks for your time 🙏

so you need to change aplicationId to default id..??
I tried to change all my version code applicationId so I can define it as another app, but it always returns undefined even though successfully build, can you help..??

@harastaivan
Copy link

I was updating my app from React Native 0.57 to 0.61.3 ran into a lot of issues and unlinked all packages, since newer React Native introduced auto-linking.

  • That didn't work so I needed link it back: react-native link react-native-config.
  • That still wasn't enough so I needed to add apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" on the 2nd line of android/app/build.gradle, because I didn't have it there before the update.

@chepitoco
Copy link

chepitoco commented Nov 5, 2019

It works for me:

Adding -keep class com.mypackage.BuildConfig { *; } to android/app/proguard-rules.pro

@elijahmurray
Copy link

elijahmurray commented Jan 7, 2020

I got this working through some experimentation. For me, I'm using yarn workspaces so my node_modules folder is up a directory, and that's why it was failing. I just replaced the suggested line with a direct import of the needed file.

In your app/build.gradle, replace:

apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

Replace with:

apply from: "../../node_modules/react-native-config/android/dotenv.gradle"

Or in my case and using yarn workspaces, replace with:

apply from: "../../../node_modules/react-native-config/android/dotenv.gradle"

@parnekov
Copy link

Did you do the Android setup?

https://github.com/luggit/react-native-config#extra-step-for-android

Works!

@dipeshkoirala21
Copy link

@LuizFBrisighello Hi, did you resolve your undefined issue with Product Flavor? I am getting undefined too.

@nitzanw
Copy link

nitzanw commented Oct 18, 2020

me too! what's the solution?

@LuizFBrisighello
Copy link

@dipeshkoirala21 Sorry for the late answer and its not a very good news, at the time I figured out but now it was over a year ago.. I really dont remeber.

Im still on RN 0.60.5, using react-native-config 0.11.7
I think following extra-step-for-android in the link down bellow fixes it

Did you do the Android setup?

https://github.com/luggit/react-native-config#extra-step-for-android

@mahisaajy
Copy link

Did you do the Android setup?

https://github.com/luggit/react-native-config#extra-step-for-android

it works for us

@eporomaa
Copy link

In our case, we could not read the .env file because we used a suffix for our application name, (.qa).
Adding resValue "string", "build_config_package", "com.our_app" as such to the android/app/build.gradle solved it for us:

...
   productFlavors {
        dev {}
        qa {
            applicationId 'com.our_app.qa'
            resValue "string", "build_config_package", "com.our_app" // Required for react-native-config to find .env
        }
    }
...

@cutePanda123
Copy link

cutePanda123 commented Mar 21, 2021

After I installed react-native-config and added the .env file to my project's root, I found the environment variables were still not included in the Config object.
I tried all the mitigation approaches without making it work. Finally, I double-checked the react-native-config package's instruction(https://github.com/luggit/react-native-config) and found the extra step for Android matters. As I am focusing on building an Android app now, I have not verified if iOS works or not.

Extra step for Android
You'll also need to manually apply a plugin to your app, from android/app/build.gradle:

// 2nd line, add a new apply:
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv

In a summary, what I did to make it work:

  1. yarn add react-native-config
  2. npx react-native link react-native-config
  3. Note: for the above step, it seems like adding "new ReactNativeConfigPackage()" to MainApplication.java is not needed. I tried to add it and got an error from the Android emulator indicated that this package was added twice.
  4. Add "apply from: project(':react-native-config').projectDir.getPath() + "/dotenv" to the 2nd line of android/app/build.bradle
  5. npx react-native run-android
  6. It just worked \^w^/

My changes can be found from this commit. Hope it helps.
cutePanda123/pure-listener@b406e04

@MGhufranKhalil
Copy link

Did you do the Android setup?

https://github.com/luggit/react-native-config#extra-step-for-android

work for me

@WillyRamirez
Copy link

I was updating my app from React Native 0.57 to 0.61.3 ran into a lot of issues and unlinked all packages, since newer React Native introduced auto-linking.

  • That didn't work so I needed link it back: react-native link react-native-config.
  • That still wasn't enough so I needed to add apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle" on the 2nd line of android/app/build.gradle, because I didn't have it there before the update.

this worked for me.
I am on
"react-native": "0.64.0",
"react-native-config": "^1.4.2",

@blazlew
Copy link

blazlew commented Jul 28, 2021

In our case, we could not read the .env file because we used a suffix for our application name, (.qa).
Adding resValue "string", "build_config_package", "com.our_app" as such to the android/app/build.gradle solved it for us:

...
   productFlavors {
        dev {}
        qa {
            applicationId 'com.our_app.qa'
            resValue "string", "build_config_package", "com.our_app" // Required for react-native-config to find .env
        }
    }
...

Thanks, it was also my issue. You can use the applicationIdSuffix for each flavor instead of providing full package name every time.
Also, I was able to resolve the issue for all flavors using applicationIdSuffix in one place like so:

...
defaultConfig {
        applicationId "com.our_app"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        resValue "string", "build_config_package", applicationId
    }
...

@xgenem
Copy link

xgenem commented Sep 8, 2021

Figured the issue is related to different applicationId. Only when different this plugin won't work.

@yogendrajs
Copy link

Hey, this is working for debug mode, but not for staging/prod for Android. I've done everything being provided above. Any workaround? Also, what if I want to access .env.prod?

@Eliajn
Copy link

Eliajn commented Dec 1, 2021

Screen Shot 2021-12-02 at 12 27 49 AM

I am trying to create a signed bundle release from android studio preview, after the build is successful, the env variables does not exist, after extracting the apk file from the bundle release and trying it on an android device.

@SirCameron
Copy link

Is there a solution to this?
when I run ENVFILE=.env.staging npx react-native run-android --variant=release

I get this in the output:

> Configure project :app
Reading env from: .env.staging

this all works without variant=release.

@Y-k-Y
Copy link

Y-k-Y commented Aug 30, 2022

-keep class com.mypackage.BuildConfig { *; } in android/app/proguard-rules.pro worked for me!

My environment

  • RN 69.1
  • react-native-config 1.4.6

@buuhvprojects
Copy link

Windows 10 Mobile Device Nexus 6P react-native-cli: 2.0.1 react-native: 0.38.1 SET ENVFILE='.env.prod' && react-native run-android

when i run above line on example application its not reading anything from .env file.

Its simple but unexpected. Doesnt use import { SOME_ENV } from 'react-native-config'; when build it, the lib doenst reconize it. You need always use: import Config from 'react-native-config'; so Config.SOME_ENV

@SanjanaTailor
Copy link

@bericp1 I started using RN 0.60.5 and for simple $env:ENVFILE=".env.mycustomenv"; react-native run-android works fine! But adding productFlavors in that mix fucks me up. Running $env:ENVFILE=".env.mycustomenv"; react-native run-android --variant=myvariantDebug

I still get: > Configure project :app Reading env from: .env.mycustomenv

but Config.MY_ENV_VAR always returns undefined Any ideas?

I am also facing an issue.

@markmarkoh
Copy link

We were having this issue because of Proguard, as far as I could tell. Disabling Proguard in our release builds fixed it, but obviously we wanted Proguard back in.

I fixed this issue using the -keep class in the proguard-rules.pro file mentioned here: https://www.npmjs.com/package/react-native-config/v/0.11.6#problems-with-proguard

The important part is:

Problems with Proguard
When Proguard is enabled (which it is by default for Android release builds), it can rename the BuildConfig Java class in the minification process and prevent React Native Config from referencing it. To avoid this, add an exception to android/app/proguard-rules.pro:

-keep class com.mypackage.BuildConfig { *; }
mypackage should match the package value in your app/src/main/AndroidManifest.xml file. <-- super important

@RanvijayChouhan12
Copy link

RanvijayChouhan12 commented Jan 31, 2023

Finally i have Solved the Issue

MY Packages and Configs:

"react": "18.1.0",
"react-native": "0.70.6",
"react-native-config": "^1.5.0",

To Ceate the REACT_NATIVE_CONFIG https://github.com/luggit/react-native-config

follow the Above setup to to install and After installetion follow this

  1. Create Your .env File such as .env , .env.production , .env.test etc in your Root of the Project

  2. in android/settings.gradle Paste the Below Lines

include ':react-native-config'
project(':react-native-config').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-config/android')

  1. in android/app/build.gradle paste the below Line just below the apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
OR
apply from: "../../node_modules/react-native-config/android/dotenv.gradle"

Then

project.ext.envConfigFiles = [
    dev: ".env",
    test: ".env.test",
    production: ".env.production",
]

make Changes as your Requirements

THEN add these Configs just Above the : defaultConfig

flavorDimensions "default"
    productFlavors {
        Dev {
            applicationId "com.myapp.app"
            minSdkVersion rootProject.ext.minSdkVersion
            targetSdkVersion rootProject.ext.targetSdkVersion
            versionCode 1
            versionName "1.0"
            buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
            resValue "string", "build_config_package", "com.myapp.app"
        }
        Test {
            applicationId "com.myapp.app"
            minSdkVersion rootProject.ext.minSdkVersion
            targetSdkVersion rootProject.ext.targetSdkVersion
            versionCode 1
            versionName "1.0"
            buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
            resValue "string", "build_config_package", "com.myapp.app"
        }
        Production {
            applicationId "com.myapp.app"
            minSdkVersion rootProject.ext.minSdkVersion
            targetSdkVersion rootProject.ext.targetSdkVersion
            versionCode 1
            versionName "1.0"
            buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
            resValue "string", "build_config_package", "com.myapp.app"
        }
    }

also don't Forget tio ADD at the end of your defaultConfig

resValue "string", "build_config_package", "com.myapp.app"

THEN ADD
matchingFallbacks = ['debug', 'release']

in the buildTypes.debug

in the dependencies add
implementation project(':react-native-config')

  1. in android/app/proguard-rules.pro Paste the Below Line

-keep class com.transportsimple.appId.BuildConfig { *; }

NOTE : Please replace com.transportsimple.appId with your APP Package

Your are DONE for the ANDROID Setup of the .env File

Now to Run the APP Please run the following command.

"android": "react-native run-android --variant=devDebug -- --reset-cache",
"android:release": "react-native run-android --variant=devRelease",
"android:test": "react-native run-android --variant=testDebug",
"android:test-release": "react-native run-android --variant=testRelease",
"android:prod": "react-native run-android --variant=productionDebug",
"android:prod-release": "react-native run-android --variant=productionRelease",

to Build the APK Please do the Following:

"android:build_apk-dev": "export ENVFILE=.env && cd android && ./gradlew assembleDevRelease",
"android:build_apk-test": "export ENVFILE=.env.test && cd android && ./gradlew assembleTestRelease",
"android:build_apk-prod": "export ENVFILE=.env.production && cd android && ./gradlew assembleProductionRelease",

To Build AAB File run Folllowing :

"android:build_aab-dev": "export ENVFILE=.env && cd android && ./gradlew bundleDevRelease",
"android:build_aab-test": "export ENVFILE=.env.test && cd android && ./gradlew bundleTestRelease",
"android:build_aab-prod": "export ENVFILE=.env.production && cd android && ./gradlew bundleProductionRelease"

Thanks for Refering this 💯 👍🏻

🥇 👍🏻

@humayunkabir
Copy link

Same problem with ENVFILE=.env.prod cd android && ./gradlew assembleRelease , even with

apply plugin: "com.android.application"
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"

Working fine with react-native run-android debug mode.

This works for me, Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests