Hiding Your API Key

in a React App

Kayla Budzeak
2 min readSep 24, 2021

Hey everyone! This week I’ve been working on another special project: a special request from my dad to create a family website, on which the data from their personal weather stations (pws) can be shared.

Luckily I was able to get access to their pws’ API and its key so I already have existing data to work with 😊 but now I needed to find a way to be able to fetch to the API, but hide the key so I didn’t push it up into a public repository. Thus this week’s topic: hiding your API key in a React App!

  1. Let’s first start off by adding a .env file to the root directory of our application. Seen just above our .gitignore file in the image to the left.

2. Next, we’ll add our env variables within our new .env file. Since we are in a React app we have to use the prefix `REACT_APP_` before the name that we would like to use for our variable in order for it to be read, like so: REACT_APP_MY_API_KEY = XXX “XXX” would be where you place your actual key.

3. Now, this next part is really important, as it is what allows us to not push this up to our repository and putting out in the open. We have to add our .env file to our .gitignore file.

Below, you can see these steps all in place.

You can add a comment like the one above if you’d like in your own file, or you can add a different one, but I would make sure to leave a comment as to what the file is.

Now you might be asking yourself “Well this is great and all, but now how do I access the darn thing?” I am here to tell you this is honestly the easiest part.

Go to your file where you are sending your fetch request, where you have your API call, and where you put your API key you instead enter process.env.REACT_APP_YOUR_KEY_NAME

fetch(`https://your-api-url.com/apiKey=${process.env.REACT_APP_YOUR_KEY_NAME}`)
...

From here you can push your code up to your repository without exposing your API key, and still, be able to fetch your data!

--

--

Kayla Budzeak

I'm a Full-Stack Software Engineer, with a background in customer service, who recently graduated from Flatiron School. In my down time I love to bake & garden.