by Sai gowtham

How to define a use environment variables in React app

Environment variables help us to use different configurations in our react app for example we can use different API for development and different for production without changing the whole app every time or hiding the feature which is not ready for production yet.

Defining Environment Variables

To define environment variables, first we need to create a file .env file in the root folder of our react app.

Now, we can define environment variables inside that file using REACT_APP_.VARIABLE_NAME=VALUE.

.env
REACT_APP_.BASE_URL=https://google.com

Note: Don’t commit .env file to your public GitHub repository, if you stored secrets like API_KEY or passwords.

Accessing Environment Variables

In our react app components, we can access the environment variables by using process.env.REACT_APP_.BASE_URL.

App.js
import React from "react";

export default function App(){
   return (
      <div>
        <a href={process.REACT_APP_.BASE_URL}>My app</a>      </div>
   )
}

Inside the public/index.html file we can access environment variables like this.

index.html
<base href="%REACT_APP_BASE_URL%">

The environment variables are injected into the app at build time.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course