How to define and 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
.
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
.
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.
<base href="%REACT_APP_BASE_URL%">
The environment variables are injected into the app at build time.