Hiding your API Keys

Evelyn Hernandez
2 min readJun 12, 2021

I believe that just about every developer has pushed their project on GitHub and accidentally forgotten about hiding the API Keys. I and 2 other classmates made this rookie mistake when we were students at Flatiron. Luckily, nothing terrible happened, the project was taken off of GitHub ASAP. But bad things can happen, you can actually get billed a hefty amount of money! So be CAREFUL and always hide your API Key.

Photo by Yancy Min on Unsplash

Okay, so how do I hide my API Key? (using React)

  1. create a .env file in the root of that project’s directory, it should look like this:
- Project-Folder
- node_modules
- public
- src
- .env <-- create this file
- .gitignore
- package-lock.json
- package.json
- README.md
- yarn.lock

2. Inside of your .env file, prepend REACT_APP_ to the API Key name of your choice and assign it, your API Key:

// .env
REACT_APP_API_KEY=123a456b789c
YOU HAVE TO PREPEND REACT_APP_ no if's or but's about it.**BAD Example**
API_KEY=123a456b789c <-- DON'T do this

3. Add the .env file to the .gitignore file:

// .gitignore# dependencies
/node_module
...
# api keys
.env <-- add this inside of your .gitignore file

The .gitignore file is a text file that tells Git which files or folders to ignore in a project.

4. Verify that the .env file is not in the list of changes to be committed by running git status

Awesome, now how do I access the API Key?

To access your API key you can use the process.env object. To log your API Key, go to app.js and console log it:

// App.jsimport './App.css';console.log(process.env.REACT_APP_API_KEY)function App () {
...
}

Make sure to delete the console.log before committing your code!

When you are fetching data, make sure to use the backticks `` so you can interpolate process.env.REACT_APP_API_KEY:

const { data } = await axios.get(
`https://api.somesite.org/somedata?api_key=${process.env.REACT_YOUR_KEY}`
);

What if I forgot to do this process and I’ve already committed to Git Hub

  1. DON'T PANIC!!
  2. Execute the following command: git rm --cached path/to/file.
    The --cached flag is used if you want to keep the local copy but remove it from the repository:
$ git rm --cached .env <--.env file will be removed from the repo

3. Verify that the file has been deleted from version control by typing git status

That’s all she wrote folks! Stay safe and happy coding!

--

--

Evelyn Hernandez

I’m a FrontEnd Dev that enjoys learning & failing. With every unknown adventure comes failure, but only those who dare to fail greatly can ever achieve greatly.