how to use Environment Variables keep your secret keys safe & secure!


Avoid (accidentally) committing (exposing) your private keys, passwords or other sensitive details(by hard-coding in them in your script) to GitHub by storing them as environment variables. See the example like this

There is a story of a person who pushed aws keys to github:

Accidentally pushing API keys to GitHub can be an Expensive/Stressful Lesson:

What is Environment Variable?

An environment variable is a KEY=value pair that is stored on the local system where your code/app is being run and is accessible from within your code.


Follow these steps:

  1. List all the Default Environment Variables
$ printenv

2. For storing our secret data like tokens, API keys, passwords create a file named app-env

export API_KEY="ABDJFdfrpf956irjglkfmgi5kgf"
export TOKEN="213j29rhdfn94htrfuh94"

3. Source this file into local environment using source command

$ source app-env

4. Now we can use these environment variable in our program as for example in NodeJS:

Node.js gives you access to the variables defined in your environment in the process.env global object.

So we can use process.env object to access our keys

var api_key = process.env.API_KEY;

5. and last thing add app-env to .gitignore so this file is ignored to .git


This way we can use our keys and tokens in our local environment and be safe from getting these sensitive data exposed to others on Github.


Topics of interest

More Related Stories