How can we set up .env
in react native application? How to do environment setup inside react-native.

- 15,447
- 5
- 79
- 98

- 105
- 1
- 2
- 7
-
in my case for `ios` i use `.plist` file and for `android` the `flavors`. – jose920405 Oct 31 '18 at 19:20
4 Answers
I use 'react-native-dotenv' package. Install it and add "react-native-dotenv" preset to your .babelrc file at the project root, like this:
{
"presets": ["react-native", "react-native-dotenv"]
}
Then create a .env file and add your properties there, may be like this:
YOUR_FIELD="value"
finally, you should be able to use it in your src files, like this:
import { YOUR_FIELD } from 'react-native-dotenv';
console.log(YOUR_FIELD) // prints "value"
if you run into an issue while using this package, then you can look for further clarification in their GitHub page, right here: https://github.com/zetachang/react-native-dotenv
Hope this helps.

- 1,468
- 2
- 16
- 21
-
found this article explain to me more with screenshot: https://www.freecodecamp.org/news/how-to-gracefully-use-environment-variables-in-a-react-native-app/ – hendra1 Aug 18 '19 at 04:06
-
1Heads up (maintainer here): make sure to move `react-native-dotenv` to `plugins` in `v2.x.x` and change `import { YOUR_FIELD } from 'react-native-dotenv';` to `import { YOUR_FIELD } from '@env';` – Kemal Ahmed Feb 11 '21 at 20:08
-
For those who are looking at this in 2022 babel.config.js should be `module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: [ ["module:react-native-dotenv", { "moduleName": "@env", "path": ".env", "blacklist": null, "whitelist": null, "safe": false, "allowUndefined": false } ] ] }; ` and import must be `import { YOUR_FIELD } from '@env';` – Meenohara May 06 '22 at 14:48
In React Native CLI First install https://www.npmjs.com/package/react-native-dotenv this package Then Create .env file in your Route Folder of your project and set urls like this
REACT_APP_API_BASE_URL='https://api/v1'
REACT_APP_BT_AUTHORIZATION='....vynf6nzv'
After this, Create Config.js file in Route Folder and import your URLS like this
import {REACT_APP_BASE_URL, REACT_APP_API_BASE_URL} from '@env';
export default {
REACT_APP_BASE_URL,
REACT_APP_API_BASE_URL,
};
To Use these URLS You can simply import config file in any file you want and use it like this one //Importing config file
import config from '../../../config';
//Using config file to set urls
**`${config.REACT_APP_API_BASE_URL}/user_requests`**
Thanks.

- 190
- 1
- 3
- 15
Two options
1) If you are using a project with native code, you can use react-native-config
. This gives you the added benefit of using your .env
variables in your android and iOS project files.
2) If you are using expo, react-native-dotenv
is the way to go.

- 5,664
- 3
- 32
- 65
For those using expo in 2023, there are two options recommended by their docs - docs.expo.dev/guides/environment-variables/
See more details in this answer: stackoverflow.com/a/75417112/1550202

- 944
- 7
- 10