0

Today I was trying to write an environment variable like this:

set PORT=5000

But when I access it through the process.env.PORT variable in node, it gives undefined.

I might be missing something or my PC is malfunctioning, so any help would be appreciated, Thanks

2
  • 1
    Setting environment variables doesn't retroactively change the environment of already running processes. Commented Jan 16, 2021 at 14:02
  • Sorry, can you explain it more lightly? Commented Jan 16, 2021 at 14:23

1 Answer 1

1

use the below command to set the port number in node process while running node JS program. And this port will only limited to this node process.

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

I recommend you using .environment file to keep your configuration separate.

Steps to follow:

  • create a package.json file
  • install the dotenv npm package
  • write the code to read the .env
  • run the code

.env

# .env.example
NODE_ENV=development
PORT=8626
# Set your database connection information here 
API_KEY=your-core-api-key-goes-here

server.js file:

// server.js
console.log(`Your port is ${process.env.PORT}`); // undefined
const dotenv = require('dotenv');
dotenv.config();
console.log(`Your port is ${process.env.PORT}`); // 8626

for more details you can check this: https://www.twilio.com/blog/working-with-environment-variables-in-node-js-html

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much. I tried with dotenv and it worked!! I was adding authentication to my app, but when I had to access the private key for jwt in the environment variable it gave me undefined and I got frustrated, but it works now, thank you!
Right, but when I host my app won't this file be available to anyone who can access my codebase? Can't they just read the secrets in the .env file?
Environment variables exist outside our application's code, they are available where our application is running. For that to work you can go this article : stackabuse.com/…
Got it, so when I host I host my app to Heroku, etc. they'd allow me to set the environment variable there itself, so I don't need to configure the .env file. Right?
No, you don't need to add .env file to heroku env instead heroku gives they provided their own env setting to make it work. Remember never add this file as a part of your source code. check this out : dev.to/numtostr/comment/k026

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.