DEV Community

Himanshu Gupta
Himanshu Gupta

Posted on

What is environment variables in Node.js and how to use it.

Environment Variables are variables that are set by the Operating System. They are decoupled from application logic. They can be accessed from applications and programs through various APIs. There is a Node. js library called dotenv that helps you manage and load environment variables.

There is a Node.js library called dotenv that helps you manage and load environment variables. Let’s take a look at the purpose of environment variables, how to use them, and their role in a development environment.

How to get & set environment variables in Node.js
const port = process.env.PORT || 3000; // For Set variable
app.listen(port, () => {
console.log(Server is running on the port ${port}.);
}); //For Get
If production server then do X else if test server then do Y else if localhost then do Z …Example:-

if (process.env.NODE_ENV === ‘production’) {

//here is code for server

// }

// else {

//Here is Localhost code

// }

Reference Links

https://nodejs.dev/learn/how-to-read-environment-variables-from-nodejs

https://www.freecodecamp.org/news/how-to-use-node-environment-variables-with-a-dotenv-file-for-node-js-and-npm/

Thank you for keep reading. If you liked the article, please hit the 👏button; if you want to see more articles follow me on medium😘.

If you have any doubt or suggestion🤔 when going through this practical, please leave us a comment below👌.

See you in upcoming articles😊. Keep in touch with medium. 🤗🤗

Top comments (0)