Environment variables not changing in Node.js

Viewed 2608
  1. set NODE_ENV=production not working in my pc. NODE_ENV is not changing from "development"

    if(app.get('env') === 'development'){
        app.use(morgan('tiny'));
        console.log("Morgan enabled...");
    }
    
  2. set PORT=5000 not working - PORT is not changing from "3000".

    const port = process.env.PORT || 3000;
    app.listen(port, () => console.log(`Listening on port ${port}...`));
    
2 Answers

As a Windows user, I had problems in the past with exporting / setting environment variables for node to use.

I ended up using the dotenv NPM package since you can be sure it correctly loads the environment variables regardless of what system you are developing on.

Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env.

First, install and save it:

npm i dotenv

Create a file in the root of your project called .env

PORT=5000

You can set any number of variables using simple X=Y syntax.

Then, somewhere in your code:

require('dotenv').config();

// my main application code

With the above example, you now have access to process.env.PORT which will equal 5000 (value set from the .env file)

Note: Avoid storing .env in your version control by adding a .gitignore rule:

node_modules/

# Other ignore rules...

# Add this line
.env

Good luck!

you should be installed dotenv by yarn add dotenv then make file to in the folder .env in the server or the main page for app add this code

const dotenv=require('dotenv').config({path:'./env})

//this depand where are you store the .env and the name file for path and in the file .env make variable PORT=3000

Related