Environment variables and hiding secrets

Photo by FLY:D on Unsplash

Environment variables and hiding secrets

How to not push your API Keys to GitHub

Introduction

We often use API Keys in our projects to integrate with a cool service out somewhere on the internet. These Keys should be kept very private since they are like usernames and passwords and anyone with access to them can make calls to the API on your behalf. This in some cases can be very harmful. So clearly, hardcoding them in your source code is not a good idea, especially if you push your code to GitHub.

Let us learn some strategies so that you do not leak your Keys into a public GitHub repo.

Steps to safeguard your keys

The .gitignore file

This is a special file which, when present in a repository is ignored by git and is not tracked. Learn more about how .gitignore works here. But if you hardcode the API Keys in your source code, how can you possibly ignore your source file? This is where the .env file comes into play.

The .env file

You can easily create a file called .env and put your API Keys in it. For example:

API_KEY = "<your api key here>"

You can also add other secrets like ENV, PORT, a consumer token, etc. Just mention them on separate lines. Now you can add this file to your .gitignore and you're good to go.

You can draw these variables into your application. This process varies for different programming languages. Let us take a look at how to do this in Python.

The python-dotenv module

You can install it via pip

pip install python-dotenv

Now import it

from dotenv import load_dotenv
load_dotenv() # This tells the interpreter to take environment variables from the .env file

Finally use the environment variables in your code

import os
api_key = os.getenv("API_KEY") # Replace API_KEY with the name of your environment variables, if needed

You can now use this api_key variable instead of your hardcoded value

Final thoughts

Something valuable you can do for someone using your project on GitHub is to include a .env.sample file in which you mention the environment variables that your application needs to run

API_KEY = "<your api key here>"
TOKEN = "<your secret token here>"
...

Bonus tip: If your API Key ever gets leaked, most API services have an option to revoke your key. Use this feature and you will have a new key, and the old one will no longer work. And follow the above steps to not leak your new Key :)

I hope you learnt something. Till next time, keep your apps safe and happy coding