Setting Environment Variables in ReactNative

An environment variable is a dynamic-named value that can affect App from outside controllers.API Keys, Secret Token, IOS, Android Keys always contain sensitive information which needs to be secure , and meanwhile some config needs to be done from external sources , for example Android Key / IOS Key need to be set through Gradle /Xcode. In such case we require Environment variables(.env).

Photo byPankaj PatelonUnsplash

Requirements

To follow this tutorial, Basic Knowledge of Reactnative and configurations required.Create basic project setup using Expo init or ReactNative Cli

Getting Started

There are several ways to set up environment variables(.env) , here we are going to set up through react-native-dotenv. This will help to manage environment variables gracefully throughout the app.

Install react-native-dotenv using

npm install react-native-dotenv --save-dev

Or

yarn add react-native-dotenv

Now create the “.env” file in the root folder and open it and enter config keys. For example,

API_URL: http://rukstech/sample
KEY: awndcdgtytgokfokpoklsweeurhjv

Configuration

The package react-native-dotenv will help to import all the above environment variables from a .env file. For this we need some configuration.

Open babel.config.js and modify presets like below.

module.exports = {
presets: [
'module:metro-react-native-babel-preset',
'module:react-native-dotenv'
]
}

Now , environment variables can import anywhere inside application using below statement

Import { API_URL,KEY} from ‘react-native-dotenv’

Conclusion

In this way,all mobile OS configuration can be made easy.No need to add any native code to integrate for each mobile OS platform separately.

© 2020 RuksTech