SAM
SAM

Reputation: 1121

Why use process.env.PORT in Node.js?

I was learning Node.js and came across this code:

const express = require("express");

const app = express();

app.get("/", (req, res) => res.send("Get request received"));

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => console.log("Server started"));

but what confuses me is that why we need to use here process.env.PORT || 5000, that is, what is the point in using process.env.PORT and why not just use const PORT = 5000;

Upvotes: 2

Views: 2431

Answers (2)

Abhishek T.
Abhishek T.

Reputation: 1133

In many cloud environments (e.g. Heroku,AWS), you can set the environment variable PORT to tell your web server what port to listen on.

If you pass 5000 hard-coded to app.listen(), you're always listening on port 5000, which might be good just for developing at your localhost, or not, depending on your requirements.

So process.env.PORT || 5000 means: what is in the environment variable PORT, or if there's nothing then use default given port 5000.

Hope you got it.

Upvotes: 1

Adithya Sreyaj
Adithya Sreyaj

Reputation: 1892

This a concept of using Environment Variables for certain configurations in your application rather than hard-coding them in your source files.

When you finally deploy applications in any service, We might have to mess around the port where the application is set to run. So if you hard-code it in your code, you have to go back and change it in your code every time, you make any change in your deployment configuration.

So instead, you use process.env.PORT to tell your application to take the PORT by reading the Environment Variable.

You put the || just to make sure that if the PORT variable by any chance was not found, use the specified port instead.

Here is a good read: https://www.twilio.com/blog/2017/08/working-with-environment-variables-in-node-js.html

Upvotes: 1

Related Questions