Add .env
support to your react-native application without including credentials in JavaScript bundle.
Package that loads environment variables from a .env
file into process.env
. Credentials are not included in the JavaScript bundle, instead credentials that are bundled in the native app are exposed to the Javascript. It's a much more secure way for you application to access credentials, especially when JavaScript bundles are being remotely downloaded. You can easily use .env
file and let build process create platform specific configuration files.
NOTE: Android not supported yet, feel free to contribute :)
yarn add react-native-dot-env
# or
npm install --save react-native-dot-env
react-native link react-native-dot-env
Add the following line to your build targets in your Podfile
pod 'RNDotEnv', :path => '../node_modules/react-native-dot-env/ios'
Then run pod install
Sorry, Android is not supported yet.
- Create a new React Native App
react-native init SimpleApp
cd SimpleApp
- Install the latest version of react-native-dot-env
yarn add react-native-dot-env
# or via npm
# npm install --save react-native-dot-env
react-native link react-native-dot-env
- Create .env file(s) and add them to .gitignore
echo "API_URL=http://localhost" > .env
touch ios/.env.plist
echo ".env*" >> .gitignore
- Add newly created
.env.plist
to Xcode project
open ios/SimpleApp.xcodeproj
- In Project navigator right click on project
SimpleApp
(root item) and chooseAdd Files to "SimpleApp"
- Add the newly created
.env.plist
(in MacOS you can show hidden files with⌘+shift+.
)
- Add
Run script
in ProjectBuild phases
- It has to be before
Copy Bundle resources
(see image)
node ../node_modules/react-native-dot-env/cli.js -e ../.env -d $SRCROOT
- Add to application source code
import dotenv from 'react-native-dot-env'
dotenv()
console.log(process.env)
- Run App
react-native run-ios