How to access Environment Variables in your React Application

Hashini Samaraweera
2 min readNov 17, 2019

When working with react, one might, well… one will almost always, need to store and retrieve environmental variables. After scouring the internet for hours, I landed on a module named dotenv, which assisted me with the task at hand. It helps to load the variables on your .env file to .process .env. which can then be accessed from where ever you want in your app.

So to start off, let’s create our react app and navigate into it.

npx create-react-app react-app
cd react-app
npm start

Next, you can create your .env files in the root folder and add your environmental variables into it.

However, bear in mind that all the variables in the .env file must be in the following format :

REACT_APP_(whatever-name-you-prefer)

sans the brackets.

Next, you should install dotenv with one of the following commands:

npm install dotenv 
yarn add dotenv

Next make sure to configure dotenv at the earliest opportunity by placing it, preferably in your index.js as below.

require(‘dotenv’).config().

That’s it. You’re done. Now to access the variables from where ever you want within your project src, simply type process.env.(the-name-of-your-variable) as shown below in an example:

.env file

REACT_APP_BASEURL = ‘ https://www.npmjs.com/package/dotenv

config.js file

const baseURL = process.env.REACT_APP_BASEURL

Make sure the prefix REACT_APP_ is there and not just the name.

Happy coding!

--

--