Home > Software engineering >  Node.js - I can't access config variables in app.js
Node.js - I can't access config variables in app.js

Time:07-08

As the name says, I am a hobbyist developer. I am learning node.js, which I really like. Unfortunately, I've hit a problem. In app.js I can't get to the environment variables.

My set-up is:

Windows 10 PC

VS Code 1.68

In package.json:

"scripts": {
    "start": "nodemon server.js"
  },
// and...
"dependencies": { 
"dotenv": "^16.0.1", 
"express": "^4.18.1", 
"morgan": "^1.10.0", 
"mysql2": "^2.3.3", 
"sequelize": "^6.21.2" 
}

When I type process.env. <-- a drop-down in VS Code appears here but my variable NODE_ENV is not in the list.

Screenshot added

In config.env I have:


NODE_ENV=development

PORT=8000

UZERNAME=john

PASSWORD=123456x

In server.js I have:

const dotenv = require('dotenv');

const app = require('./app');

dotenv.config({ path: './config.env' });

console.log(process.env); // <-- The list displayed here includes my variables from config.env...

... I can see see my variables in the console, e.g.


UZERNAME: 'john',  <--- this is my variable.

Any suggestions?

Thanks.

CodePudding user response:

hope helpful for you Method 1

process.env.UZERNAME

Method 2

process.env["UZERNAME"]

CodePudding user response:

You need to load config before importing app.js

const dotenv = require('dotenv');

dotenv.config({ path: './config.env' });

const app = require('./app');

console.log(process.env);
  • Related