← back to Blog

Using environment variables in a React Native App.

Written by: Victor Bruce

3rd March 2020

|

1 min read

environment variables in react-native

Install react-native-dotenv library/package by running the command:

npm i react-native-dotenv

For iOS,

  1. cd /ios
  2. pod 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 = 1234;

Next, 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.json file and add the line below inside the “compilerOptions”: {} object:
"typesRoots": ["./src/types"]
  • Now back to the env.d.ts file, 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!