Marek M
Marek M

Reputation: 87

NodeJS: How is the value for process.env.PORT assigned?

When I run my NodeJS app the process.env.PORT is undefined. I am noticing this when I try to log the value:

console.log(process.env.PORT) // undefined

My question is, how to I change that environment object value? Thanks for an answer!

Upvotes: 1

Views: 1699

Answers (2)

Dacre Denny
Dacre Denny

Reputation: 30390

The process.env.PORT variable returns the value of the PORT environment variable.

If for example app.js is your apps entry point, then accessing process.env.PORT from within your app would yield a value of 8080 if you were to run this on the terminal:

PORT=8080 node app.js 

Update

To specify the PORT environment variable when running your app on Heroku, login to your Heroku account, select your application from the list, click the "settings" tab and then click "Reveal Config Vars". Enter a PORT key with the required port value, and click the "Add" button.

Set env config for heroku app

Upvotes: 3

Shubhi Sood
Shubhi Sood

Reputation: 420

For getting your process.env.PORT you need to defined PORT varable in .env file defined at root level of project. Then, you need to use dotenv npm package for loading process.env variables in your project. For details about dotenv you can refer to following documentation:

https://github.com/motdotla/dotenv#readme

Upvotes: 1

Related Questions