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. 🤗🤗

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more