How to add and access .env in React?

By Mateusz Szostek on 22 Feb 2021

By default, we should not store any secrets (such as API key) in the React application. Fortunately, environmental variables can help. In this post, we'll briefly explain how to create and read them.

How to create environmental variables in React app.

Let's start from the beginning. The first step you should do is run the following command:

npm install dotenv --save

You have installed a package that will allow you to load the environment variables from a .env file into process.env. Then add the following code lines to your application:


Then create a .env file at the root directory of your application and add the variables to it. For example:

REACT_APP_EXAMPLE_API_KEY = 'my-secret-example-api-key'

At the very end, don't forget to add .env to your .gitignore file so that they never end up in the GIT repository.

How to use enviromental variables?

To use environment variables, use the process variable. How to do this is shown in the example below:


Remember to make sure that you are not trying to read the object itself because it will always return an empty object. Additionally, your .env file should be in the following location:


Finally, remember to reset the server when you've added the .env file.

Written by Mateusz Szostek

Css, Web Development

Why media queries run at wrong width?

Web developer problem. The solution is simpler than it sounds.


How to update all Node dependencies?

Are your dependecies out of date? There is a simple way to safetly update all.

C# .NET .NET Core

When should you use struct?

Struct and class. How the memory is allocated?

Top Topics

When should you use struct?Why media queries run at wrong width?How to update all Node dependencies?

Copyright © 2020 Mateusz Szostek, all rights reserved.