A better way to use Environmental Variables in Node.js

A better way to use Environmental Variables in Node.js

·

2 min read

Learning to use environmental variables, is an important habit one could inculcate. It is important, because, one wrong exposure of a critical variable in your app and your whole business could come crashing down at the hands of malicious actors, before you've even had the chance to build it up.

This article is not to teach you of the importance of environmental variables or even how to use them in your node app. This article assumes you know what environmental variables are and that you've used them before in your node js application. It assumes that you have used the "dot-env" package and only promises to show you a better and faster way to set things up.

Using the dot-env package in your node.js applications means you have to make a .env file with your environmental variables and then set the variables in your terminals. This could get burdensome if you are more than a few of those to set. The Solution? An NPM package called 'env-cmd'. It eliminates the second step of you needing to create the environmental variables manually by looking into your '.env' file, picking up the variables in there and setting things up.

How To Use

  1. Install the package from npm using
    npm install -D env-cmd
    
  2. Create a .env file and fill it up with your variables (note: you must have the dot-env package installed)

  3. In the "scripts" section of your package.json file, include "env-cmd" in whichever option you start your development server with. If you use the 'start' option i.e you spin-up your server with "npm start", your scripts object should look like the below:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "env-cmd nodemon app.js"
  }
  1. spin up your server and everything should work just fine. Visit the npm page of the package for more information on how to use