How to Hide your API keys from Github! (And why you should do it!)

Stephen James
3 min readMar 1, 2019

--

Let’s say you found an API for your application, tested it, looked at the data it returns and everything seems great. But just as you are about to push up your project to GitHub you realise there’s a problem… Your API key is exposed! *insert dramatic music*

Why is this a problem, you ask? Well, there may be unscrupulous characters combing through GitHub looking for exposed keys they can take use. And if the key you are paying for is exposed, they could use it and leave you to foot the bill.

As you can see from the image below some API calls can cost as much 5 cents per call, and if you are not careful, you might end up with a nasty surprise at the end of the month.

Convinced? Then let’s move on to the how?

Step by Step Guide to Hiding your API Key

Disclaimers: I will be using JavaScript/Node.js To demonstrate this procedure and the terminal commands are Mac OS based. This will also work for node_modules and other folders you might not want to upload to gitHub.

1. Create a Config file, inside your project folder

2. Create an object, to hold all of your API keys as strings. (I have just used a placeholder API key) With node you can export variables and functions as modules, which I have chosen to do below. If your unfamiliar with Node.js, you can also add a script tag in your HTML to the config file.

3. So how do we gain access to this Config file from a different file (like the one we actually want to make the API call)? We need to require the module and assign it to a variable.

4. Once we have required the config file, we can access it like normal. We know the config object has a key of key. So we just interpolate our string url with config.key.

So far we have separated our API keys from where they are called. But how do we stop this config file from being uploaded to GitHub?Hiding your API Key

5. GitHub has a file we can leverage called .gitignore. This file should contain any file names you do NOT wish to track on GitHub.

6. We create the .gitignore file.

7. Then we add the file names we want GitHub to ignore to the .gitignore file, makes sense right?

8. I have also added node_modules to this. As it’s quite a large file, I don’t want to constantly download or upload it, any user can just run npm install to download them.

And that’s it you’re done!

Thanks for reading. I hope this was helpful to understand why and how we should all be hiding our API keys.

--

--

Stephen James

Full Stack Software Engineer, I love to teach and help others learn about code!