Chimezie Innocent I am Chimezie, a software developer based in Nigeria. I am highly skilled in HTML, CSS, and JS to build web-accessible and progressive apps. I'm also skilled with React for web, React Native for Android apps, and Tailwind CSS. I write technical articles, too.

Understanding React Native env variables

5 min read 1452

Understanding React Native Env Variables

Variables are one of the fundamental components of programming languages. In JavaScript, a variable stores the value of data types such as integers, strings, and more. The value or data type of a variable can be changed later.

In this article, we will learn about environment variables, why they are useful, and how to use them in React Native. We will cover:

What is an env variable?

Variables can play different roles in React Native. For example, you can use CSS variables in React Native to store and implement custom styles.

An environment variable — or as it is popularly known, an env variable — is a variable whose value is set from outside the program. It is used to store information like API endpoints, directory paths, and so on.

If you want to reduce repetition in your code, using an env variable helps you DRY code. All you have to do is write or define your variable in your root folder. Then, you can import the variable in your component before calling it.

While env variables are very useful in React Native, it is not advisable to use them to store sensitive information like API keys, authentication keys, or passwords. They are not secure for various reasons.

For example, env variables do not encrypt their values. They are also embedded into the application’s build, which means that anyone can view them by inspecting your app’s files.

How to create a custom env variable in React Native

Let’s take a look at an example of creating env variables in React Native.

Your first step is to go to your root folder and create a .env file. Within this file, write the API endpoint without any parentheses, as seen below:

REACT_APP_BASE_URL=https://api-dev.application.com

Then, inside your component, call the env variable as shown in the example below:



import React, { useState, useEffect } from "react";
import { View, Text } from "react-native";

const App = () => {
  const postUrl = process.env.REACT_APP_BASE_URL
  return (
    <View
      style={{
        flex: 1,
        justifyContent: "center",
        alignItems: "center"
      }}
    >
      <Text>ENV URL: {postUrl} </Text> // https://api-dev.endpoint.com
    </View>
  );
};
export default App;

Notice how we defined the env variables in process.env. in the example above. This step allows us to use process.env. to access the env variables.

It is pertinent to note that all our custom env variables in React Native must begin with REACT_APP_. Any variables without the REACT_APP_ prefix will be ignored, and we will not be able to access them in our application.

What is NODE_ENV?

NODE_ENV is a built-in env variable that is used to state whether a particular environment is a development, testing, or production environment. Unlike our custom env variables in React Native, NODE_ENV does not need the REACT_APP_ prefix.

To use NODE_ENV to check which environment you are currently working on, you can do the following in your App.js file:

const environment = process.env.NODE_ENV
console.log(environment)

If you’re working in a development environment (i.e., when you run npm start), console.log(environment) will print development.

If you’re working in a testing environment (i.e., when you run npm test), console.log(environment) will print test.

If you’re working in a production environment (i.e., when you run npm build to push to production), console.log(environment) will print production.


More great articles from LogRocket:


NODE_ENV cannot be overridden manually, which can help keep developers from deploying a slow development build to production by accident.

Using env variables to switch between API endpoints in different environments

You can use env variables to render information conditionally based on the environment. For example, we can switch between API endpoints in development, testing, and production using NODE_ENV.

You may be wondering why environment-based rendering for API endpoints and other information is even necessary. One important reason is so that we can make changes or hot fixes in production or add new features in development without breaking the production build.

Let’s say we already have a live version of our application, but we want to add a new feature or make some other change. We do not want to make this change in the production environment because we might break the application.

Instead, we will have to switch to the development environment, make the necessary changes, and test. We could also switch to the staging environment to make sure everything is okay and nothing breaks before we push to production.

We will be building out a very simple React Native application to help demonstrate how we can use env variables to switch between API endpoints in different environments. To follow along with the rest of this article, you should know how to work with React Native.

Installing and configuring the dotenv package

There are many React Native component libraries and packages that help provide a smooth dev experience. Some packages can help us easily access our env variables in React Native, including dotenv, react-native-config, and so on.

For the purposes of this article, we will be using the dotenv package. The dotenv package allows you inject your env variable into a React Native environment.

To install dotenv with NPM, run the command below:

$ npm install react-native-dotenv

To install dotenv with yarn, run the command below:

$ yarn add react-native-dotenv

After installing the package, spin up your application. Then, let’s configure the plugins.

To configure the installed package, go to your .babelrc or babel.config.js file located in your root folder and add the following:

module.exports = {
  plugins: [
    [
      "module:react-native-dotenv",
      {
        envName: "APP_ENV",
        moduleName: "@env",
        path: ".env"
      }
    ]
  ]
};

Here, we configured our dotenv package. We also assigned a path to the .env file, where our env variables will be stored. Finally, we assigned a module named @env, from which we can import our env variables.

Defining our custom env variables in our .env file

Next, let’s create our .env file in our root folder. The .env file is a text file we will use to define our variables, as shown below.

REACT_APP_DEV_MODE=https://api-dev.application.com
REACT_APP_PROD_MODE=https://api-prod.application.com
REACT_APP_STAGE_MODE=https://api-stage.application.com
REACT_APP_TEST_MODE=https://api-test.application.com

As you can see above, we defined our custom env variables using the REACT_APP_ prefix.

Importing and calling variables from our @env module

Next, let’s go over to our App.js file and import the variables from the @env module, which we configured earlier in our babel.config.js file.

import React from "react";
import { REACT_APP_DEV_MODE, REACT_APP_PROD_MODE } from "@env"

After we have imported our variables, we can call them and fetch our API endpoints with them.

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { REACT_APP_DEV_MODE } from '@env';

const App = () => {
    return (
        <View style={styles.screen}>
            <Text>Url: {REACT_APP_DEV_MODE}</Text> // https://api-dev.application.com
        </View>
    );
};

const styles = StyleSheet.create({
    screen: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
});
export default App;

We have seen how to configure our dotenv package, create our env variables, and call env variables from our @env module. Finally, let us use this knowledge to switch between API endpoints in different environments.

Checking the environment and dynamically calling the env variable

Earlier, we learned that we can use NODE_ENV to check which React Native environment we are in. We can then switch between API endpoints conditionally based on that environment.

The below code shows two ways to achieve this. The first way is by importing the env variables we defined in our .env file. The second way is by using process.env.

// using the @env package
import { REACT_APP_DEV_MODE, REACT_APP_PROD_MODE } from '@env';

const url =
        process.env.NODE_ENV === 'development'
            ? REACT_APP_DEV_MODE
            : REACT_APP_PROD_MODE;

// Or using process.env
const url =
        process.env.NODE_ENV === 'development' ? process.env.REACT_APP_DEV_MODE : process.env.REACT_APP_PROD_MODE;

In each method, we first checked the environment, then dynamically called the corresponding env variable.

Conclusion

In this article, we saw why using env variables in React Native is important. We also learned how to create custom env variables and use them to dynamically switch between API endpoints in different environments.

I hope this article has helped you understand React Native env variables better. Thank you for reading!

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.

Start proactively monitoring your React Native apps — .

Chimezie Innocent I am Chimezie, a software developer based in Nigeria. I am highly skilled in HTML, CSS, and JS to build web-accessible and progressive apps. I'm also skilled with React for web, React Native for Android apps, and Tailwind CSS. I write technical articles, too.

Leave a Reply