Reputation: 61
I'm making a react native app that makes a request to my server hosted on heroku.
Should I be hiding the URL of my server and if so how can I add an environment variable to a react native project?
I have made a .env
file and then have done this:
console.log(process.env.URL)
Which is returning undefined - I am also using expo if that makes a difference.
Upvotes: 0
Views: 4808
Reputation: 745
One library that I like to use that works for bare react native and expo is react-native-dotenv
Install it npm i react-native-dotenv
Add a .env
file with your variables
MY_ENV_VARIABLE=SECRET_PASSWORD
.babelrc
file.{
"plugins": [
["module:react-native-dotenv"]
]
}
import { MY_ENV_VARIABLE } from "react-native-dotenv";
function doSomething() {
console.log(MY_ENV_VARIABLE);
}
Upvotes: 0
Reputation: 1719
If you use Expo, there is an easy way to create environment variables.
In your app.json
file
{
"expo": {
"extra": {
"URL": "https://..."
}
}
}
After that, you will need to install the expo-constant
package.
expo install expo-constants
And, to get the info in your app:
import Constants from "expo-constants";
console.log(Constants.manifest.extra.URL);
Upvotes: 4