how to set up environment variables

Environment Variables and how to set them

Burhanuddin Rangwala
2 min readDec 30, 2021

--

Two ways to set up environment variables for your next JavaScript project.

Everybody wants to learn the flashy stuff like React and Vue when it comes to web development. So for a change let’s get a bit into the basics, let’s discuss environment variables.

If you have ever worked on a commercial application or just with anything that involves API keys or other secret tokens you must have used environment variables. And you must also be aware of how janky they can be. So here I have compiled a bunch of ways you can setup environment variables in your next JS project without wasting 2 hours of your life.

1. Using dotenv

Dotenv is a module that loads environment variables from a .env file and loads them into process.env.
You can use this with NodeJS to easily use environment variables in your code.
Here’s how

require('dotenv').config();

That’s it. Just put this snippet at the to of your JS file and you can use environment variables.
To set these environment variables just create a .env file in the root directory of your project and add your secret tokens like this.

PORT = 1234
API_KEY = 123456789

Make sure to not include any sort of quotation marks, dotenv already assumes that the values are all strings.

Once your environment variables are setup you can just use them in any file you want by

const apiKey = process.env.API_KEY

2. Using Nodemon

Another way to use environment variables without installing any external dependencies is using a nodemon.json file. This only works if you are using nodemon.
To use this just create a nodemon.json file in the root directory of your project.

{
"env" : {
"PORT" = 1234,
"API_KEY" = "123456789"
}
}

Any thing you put in the env object in your nodemon.json file will be treated as an environment variable.

Once your environment variables are setup you can just use them in any file you want by

const apiKey = process.env.API_KEY

That’s it. There are also a ton of other very specific methods to set up your environment variables that you might need to use when using different packages or hosting services but most of them won’t require any additional change to your code.

--

--

Burhanuddin Rangwala

Software dev helping startups scale to new heights. Follow me if you want to know more about software development, startups, and me.