Using environment variables in a React Native App
Victor Bruce
Tue Mar 03 2020

Install react-native-dotenv library/package by running the command
npm i react-native-dotenvFor iOS,
cd /iospod install
Configure your babel.configure.js to allow you to inject your environment variables into your react-native environment using dotenv for multiple environments.
Basic Setup:
Inside your babel.configure.js file, add the code below:
module.exports = {
"plugins": [
["module:react-native-dotenv", {
"moduleName": "@env",
"path": ".env",
"blacklist": null,
"whitelist": null,
"safe": false,
"allowUndefined": true
}]
]
}Usage:
Create a .env file in the root of your project folder and add your environment variables.
CLIENT_ID=1234Next, import the environment variable and use it within your code like this:
import {CLIENT_ID} from '@env';
console.log(CLIENT_ID)For Projects using Typescript:
- Create a types folder
- Within the types folder create a file for example
env.d.ts - Open the
tsconfig.jsonfile and add the line below inside the “compilerOptions”: {} object:
"typeRoots": ["./src/types"]
- Now back to the
env.d.tsfile, declare an ‘@env’ module, add all your environment variables, and export like so:
declare module '@env' {
export const CLIENT_ID: string
}Wrap Up:
In this blog post, we looked at how to use environment variables in our react-native project by installing the npm package react-native-dotenv and after, configure our babel.config.js file. Finally, we created an env file and imported the environment variable in the file/source code we want to use.
That will be it for now. Kindly give me your feedback in the comments section below. Thank you!