Enviroment Variables in Node.js

 

Environment variables are very simple to use, and amazinlgy useful to have! What do they do? Well, think of them as global variables than you can set, before you launch your application.

Need a good use case? Okay, so you have a local express/mysql setup running, and you also have a live express/mysql deployment running. Chances are you will have different database configuration for each setup? Ever needed to then go and change that every time you go and do a deploy? Then environment variables are for you.

In this example, we’re just going to focus on using env’s when you run your node script.

So to begin with, lets go ahead and make two scripts in our package json


{
    ...
    "scripts": {
        "live": "node main.js",
        "dev": "node main.js" 
    }
}

Both of our scripts now are running our main.js file with node. Inside our main.js, lets put a simple little script


    console.log("It's Running!");

We can run our script now with

npm run dev

or

npm run live

and they with both do the same thing.

Now lets add an environment variable within our package.json scripts.


{
    ...
    "scripts": {
        "live": "deployment=live&&node main.js",
        "dev": "deployment=dev&&node main.js" 
    }
}

Please note, don’t leave a space between your variable value and the dual ampersands (&&) otherwise you will add a space to your string.

Now lets amend our main.js file


    if(process.env.deployment === "live") {
        console.log("I am running in a live environment");
    } else if (process.env.deployment === "dev") {
        console.log("I am running in a development environment");
    } else {
        console.log("I am running without correct setup and no environment variable was found");
    }

Now for a slightly more serious reason for using environment variables. Imagine you have some secret keys for encryption, api keys for authentication and other secure information. The LAST thing you should do,
is add it to any git commit and push it to github. Even if it’s a private repository, you just shouldn’t. So what to do here? Creating an application.json, or config.json is pretty common, and store all of your
secure information there. You will have to manually upload it to the server, and then the environment variable will decide what data to pull out of it.

That just about wraps it up for this introduction to environment variables. I’ll be writing another soon to include the dotenv.

Twitter

Error code 89: Invalid or expired token.

Stay Updated