How to hide an API key 👀

John Leavell
2 min readNov 6, 2020

Sooo yeah, about that.. I can’t recall if I was told that I need to hide my api keys but boy oh boy, I’m glad I was able to stumble on an article (found on Medium!) that provided me with some sound advice that I will never forget.

I like most junior developers have an awesome idea to make an app and making that app requires you to gather data from an external source (api) and depending on the requirements to use and view that data one must sign up on said website to gain access and then that developer is provided with a private key that allows them to use the data.

This is pretty standard, the part that isn’t standard is when you (unknowingly) push your api key to GitHub and some time later you receive a letter informing you about a bill you know nothing about.

Now the question is, how can we hide the keys?

Hide using .gitignore file

Since I’m using javaScript, I’ll discuss how to hide API keys whit that in mind.

First,

Create an external JavaScript file: Name it whatever, I used keyKey.js

Add an object containing APIK keys and export it.

module.exports = {    
"goodKey": "your developer key",
"goodSecret": "secrete",
"goodUserID": 12345
}

Second,

Add an entry in .gitignore the name of the file you created.

keyKey.*

You can now access API keys in other JS files simply by importing and requiring it.

import apiKey from '../../keyKey';...getBooksURL(){

let bookUrl = `https://getBooks.com/review/list`
let goodBooks = `v=2&key=${apiConfig.keyKey}&id=${apiConfig.goodUserID}&shelf=read&sort=date_started`;
return {bookUrl, goodBooks};
}

And that’s it! Pretty straight forward, I hope this helps someone and I hope someone will be kind enough to leave some constructive criticism.

Peace.

--

--

John Leavell
0 Followers

Full stack web developer with a passion for technology and creativity.