A common security issue that comes up when developing networked applications is where to store security credentials like API keys.

Basics

One of the first steps to securing API keys is to remember to never check them into source code repositories. If you ever commit and push code that includes a hard-coded API key, it is compromised, and you’ll need to revoke it and create a new one.

One option to store these keys is to read them from files not synced to the source code repo. The problem with this is when changing machines or working with multiple developers - its hard to pin down a consistent location to store these keys.

The next logical step is to store them in Environment Variables, which can be used consistently on any machine / operating system (e.g. using Python’s os.environ). This is what I’ve been doing until now, generally storing the keys themselves in Keepass and typing them into the shell manually using export.

Using a .env File

Instead of manually typing these keys each time, I found a good convention from Epicodus that I’m going to start using.

Create a .env file in the Git repo of you application, and be sure to include .env in your .gitignore file. On each line of this file, include the export KEY=<VALUE> line to declare all needed environment variables.

Now, at the beginning of each development session, instead of manually typing export for each specific key, just use source .env to load all your API keys.

Considerations

Please note that this method only secures against accidental key exposure in source code and version control, it will not protect against someone with root control to your box.