Using a .env in React


Looking for a crash course on how to hide your API keys or other sensitive information in your React project? Look no further! In this article, I’ll go over what a .env is and how to use it.

A .env allows you to put your environment variables in a file. This is where we are going to “hide” our sensitive information. This file gets added to .gitignore which is a text file that tells Git what files and folders to ignore in a project. We are going to start by making the .env file in the root directory like so (note that your .gitignore is also in the root directory).

Let’s say we want to add a service ID of service_123456 and a user ID of user_123456 to our project. We wanna keep those top secret 🤫 so let’s add them to our .env

In our .env we will write

Start these off with REACT_APP and then name them what you want. So if you want to also hide a password, you would use

You get the point. Note that there are no spaces in each line! Also really important step: make sure you save and restart your server each time you change something in your .env file. When you restart your server, React will gather what you wrote in the .env file.

Now how do we use this in our project? We can set it as a variable for easy access and use process.env to access it. process.env is a global injected by Node at runtime. It returns an object containing the user environment.

And that’s it! Also, don’t commit your .env files. Big no no. This is why .gitignore is so great (and it should already be there when you create a new React project).