'not able to set process.env.PORT variable in windows for node

const express = require('express'); 
const api = express();

api.get('/', (req, res) => res.send('Hello World'));

var port = process.env.PORT || 3000;

api.listen(port, () => console.log(`Listening to port 
${port}`));

I am using this command to set PORT=5000 After setting it stills show Listening to port 3000



Solution 1:[1]

You must run your file with the same CLI program (and instance) you used to set the variable value.

  • In Command Prompt: set PORT=5000

  • In Power Shell: $env:PORT=5000

  • In Bash (Windows): export PORT=5000

After that, run your program node app.js and it works.

If you're using the integrated terminal of VSCode to run your file, but using another CLI program (or instance) to set the value of PORT, is not going to work unless you change that value permanently by using setx PORT 5000 either with the Command Prompt or Power Shell (I don't know how to do it from Bash for Windows). In that case, you would need to restart VSCode for running your file with the last value of PORT.

Solution 2:[2]

It should be like this

For Command Prompt: set PORT=5000
For Power Shell: $env:PORT=5000
For Bash (Windows): export PORT=5000

Not like this

For Command Prompt: set PORT = 5000
For Power Shell: $env:PORT = 5000
For Bash (Windows): export PORT = 5000

i.e. no space before and after = sign.

Solution 3:[3]

const port = Number(process.env.PORT)

I don't know if we had the same problem, or if you ever figured this out, but I made an account JUST for this because I could not for the life of me get process.env.PORT to work, even though I was following everyone's code to the tee (no one else seems to have to explicitly convert process.env.PORT to a number). Needed to fix this problem in order to deploy my app on Heroku, which assigns the PORT variable. Can happily say it works and not lose sleep tonight :)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 David Buck
Solution 3 mallybear