Reputation: 1309
I'm new to React Native. The task at hand is to set my Google API key in AndroidManifest.xml without exposing it, when pushed to GitHub. I set up an environment variable called API_KEY, but however I want to access it in the .xml, I get an error when trying to spin up the dev server.
So far I tried:
android:value=${env.API_KEY}
android:value="${env.API_KEY}"
android:value="${API_KEY}"
Thank you!
Upvotes: 8
Views: 11466
Reputation: 31
Another solution that works for me is:
Make sure that in the .env
file is defined in the root of the project. Then:
Edit your android\app\build.gradle
with this:
apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
import com.android.build.gradle.internal.dsl.BaseAppModuleExtension
// Import dotenv and load the environment vars
project.ext.env = new Properties()
file('../../.env').withInputStream { project.ext.env.load(it) }
react {
// React Native settings
}
android {
// other code
defaultConfig {
// Use the loaded environment variable
manifestPlaceholders = [MY_ENV_VAR: project.ext.env['MY_ENV_VAR']]
}
}
And in your android\app\src\main\AndroidManifest.xml
add this:
<meta-data android:name="myEnvVar" android:value="${MY_ENV_VAR}" />
Upvotes: 0
Reputation: 101
For anyone else that the above solutions aren't working for, I had to use this syntax in android/app/build.gradle
under the android.defaultConfig
section:
manifestPlaceholders = [MY_ENV_VAR:"${System.getenv("MY_ENV_VAR")}"]
and then in android/app/src/main/AndroidManifest.xml
under the <manifest><application>
section
<meta-data android:name="myEnvVar" android:value="${MY_ENV_VAR}" />
Upvotes: 4
Reputation: 1309
Based on the second comment (from kenmistry), the solution that worked for me was indeed to create a placeholder in build.gradle, but since, for whatever reason, configuring and referring a .env file did't work, I invoked my environment variables like so in build.gradle:
manifestPlaceholders = [API_KEY: "$System.env.API_KEY"]
and accessed it in the .xml as suggested by kenmistry:
android:value="${API_KEY}"
Upvotes: 15
Reputation: 2143
assuming that you have defined the key in your .env file, you can set that up on build.gradle
as manifestPlaceholders
.
android {
defaultConfig {
manifestPlaceholders = [API_KEY: "$process.env.your_key"]
}
...
}
on your AndroidManifest.xml
,
android:value="${API_KEY}"
Upvotes: 10