izikandrw
izikandrw

Reputation: 1873

How do I pass in environment variables to Android build in react native context

My react native code uses environment variables to specify the URL of the API it hits so I can do something like this in the react-native js code: const endpoint = process.env['API_URL']

When running the app on computer it is easy to pass in the environment variable when starting the bundler: API_URL='http://myapiurl.com' react-native start

However when I generate my release apk the API_URL is not getting set.

Where do I configure this in the gradle build (or elsewhere) so that the API_URL is properly set for the generated release apk?

Upvotes: 4

Views: 9376

Answers (1)

Niels Ladekarl
Niels Ladekarl

Reputation: 359

Quick way to get it working:

Make sure you are passing in the environment variable to the gradle build command API_URL='myapiurl.com' ./gradlew assembleRelease

Another more sustainable approach:

I would recommend you to look into this project:

https://github.com/luggit/react-native-config

It allows you to specify a .env file to import variables into your code.

You can even specify different environments by naming the files

.env.{environment}

For example

.env.development
.env.production

It also allows you to specify what environment to use when bundling your application.

Here is an example for android:

project.ext.envConfigFiles = [
    debug: ".env.development",
    release: ".env.production",
]

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

These examples are taken from the readme of the project.

Upvotes: 6

Related Questions