In this post I’m going to briefly describe how to set and use environment variables.

You might be wondering why you need environment variables. Here’s an example: recently I wrote a twitterbot. The bot’s credentials were stored in a config file within the project. However, for security reasons, I couldn’t deploy the files to GitHub or to Heroku because anyone with access to those credentials would have unfettered access to my account.

So in searching for a solution, I found environment variables.

To set an environment variable in Mac is very simple. Open your terminal and type in the following command:


And that’s it!

To verify that the variable was added you can use the env command to list out all of your environment variables.

Now that you’ve set your environment variable, how do you access it? Node makes this easy. Just use:

var whoAmI = process.env.NAME;
console.log(whoAmI); // CARMEN

This is extra handy because I was able to add environment variables to my Heroku project as well, and those variables can be accessed the exact same way. Meaning, I don’t need two separate sets of logic for my home machine versus my production app.

If you add an environment variable and need to remove it, that is simple too.

unset NAME

That’s all there is to it! Just be very careful and only use unset for variables that you’ve added. Otherwise you could easily break your machine by removing something important.

Another option, if you don’t want to add environment variables to your home machine (and I wouldn’t blame you if this were the case) is to use dotenv. This handy plugin takes key-value pairs from a .env file within your project and adds them to process.env.

If you decide to go this route, it is very important that you add the .env file to your .gitignore file so that your credentials aren’t shared with the world.

I hope you’ve enjoyed this post and learned something new!

Questions? Tweet me!