The easiest way of adding env variables to NodeJS

I know there are a bunch of tutorials on how to setup env variables in nodeJS, some of them are super complicated and some of them are great and some have 5 different ways of doing it. I’d like to always just have the best and one and only solution to the same problem in all my projects, don’t you? That’s why I’ve created this article to make the adding of environmental variables super easy. Then whenever I create a new project I can look back at it and add env variables with ease.

Anyways I am not going to talk about the importance of enviromental variable, pretty much every project needs them at this point. Even if you are just connecting to a db you need environmental variables.

The simplest way of adding env variables

First we need a NodeJS project, if you need help then check out this article on how to create one. Once we are done with creating a new NodeJS project, then we’ll install library dotenv in to our project.

npm i dotenv

Then we go into our index.js file and import the dotenv library and run the config function.

require('dotenv').config()

What this does is: “config will read your .env file, parse the contents, assign it to process.env” — official documentation of dotenv

See also  How to make AWS S3 bucket files public

Once you’re done with this, you have to create an .env file with all your environmental variables. You can name them whatever, in our case for demonstration we name ours YOUR_ENV_VARIABLE. It’s a simple assignment, just like in JS, but just don’t add the in the front and the back of your string.

YOUR_ENV_VARIABLE=superSecretVariable

Now we can access our env variable in the code, by calling process.env.YOUR_ENV_VARIABLE.

console.log(process.env.YOUR_ENV_VARIABLE)

And when we run our code we can see our variable being printed.

Conclusion

So Guildsmen, hope you’ve found this article useful and whenver you need to add env variables to your NodeJS project, you’ll come back and have a look. It’s quite a simple process, but I forget it all the time. Alright have a great day and see you in the next one. 🤗

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *