Environmental Variables

The first time I used an environmental variables was on a Ruby project, which is probably why I often forget there is one more step when using them in a JavaScript. This is one of those posts that I’m sure I’ll be coming back to myself, but hopefully it helpful to someone else out there.

First, what is an environmental variable?

I know there are probably more technical terms/explanations then the following, but in its simplest form (at least the way I understand it), it’s like a variable that is set on your machine and can be accessed system-wide.

Why do I need them?

They come in really handy when you start working with API client keys, IDs, OAuth, sensitive information, etc. How so? When working on client projects or even just playing around with API’s, we are often given information that serves as a password of sort.

Say you are working on a personal project and you push your code to Github, all the code, including Ids, keys, and passwords are out there for everyone to see. In some cases, this may not be too consequential, but it can easily cause major problems that are easily avoidable. This is when environmental variables come in handy.

I store environmental variables in my bash profile. There are various ways to access it, but I open it through SublimeText.

subl ~/.bash_profile

This sets the variable in bash

export GITHUB_CLIENT_ID="xxxxxxxxxxxxxxxxxxx"

Now to get it and use it.

For Ruby: The first time I worked with environmental variables, I was learning about OAuth with Github-

ENV["GITHUB_CLIENT_ID"]

to shorten it, I assigned it to another variable

client_id = ENV["GITHUB_CLIENT_ID"]

and called it on line 8

1
2
3
4
5
6
7
8
9
get "/" do
    base_url = "https://github.com/login/oauth/authorize"
    state = SecureRandom.urlsafe_base64
    session["state"] = state
    query ={
        state: state,
        scope: "user",
        client_id: client_id,
    }

For Javascript: In this case, I was using Instagram’s API and wanted to keep my client ID hidden using Node, but overall same concept.

The bash profile step is the same

export INSTAGRAM_CLIENT_ID="xxxxxxxxxxxxxxxxxx"

In my code, I assigned it to a variable and then used it in my request

var apiKey = process.env.INSTAGRAM_CLIENT_ID;

request('https://api.instagram.com/v1/tags/' + searchTerm + '/media/recent?client_id=' + apiKey, function(error, response, body)...

One more step here, in the same terminal window you are using to run the app, run the following

source ~/.bash_profile

It’s that last step that I often forget and inspired this post.