Home > database >  I can not use env file variable values in my node project
I can not use env file variable values in my node project

Time:05-27

I have 2 variables in env file. For Port and mongoDB link. I have tried many solutions on the internet but i am not able to access the values in the listen method nor in database connection. Here is my sever file code:

const app = require("./app");
const connectDatabase = require("./config/database");

// Config
require("dotenv").config({ path: "backend/config/config.env" });

// Connecting to database
connectDatabase();

app.listen(process.env.PORT, () => {
  console.log(`Server is working on http://localhost:${process.env.PORT}`);
}); // I can run the app if i use any port number in place of "process.env.PORT"

You can see folder structure plus the variables in my env file

Note: I have put the wrong password here to hide my credentials.

I have tried to use env file in root directory also but it did not resolve the issue. The thing is i can access the values in the console but not in the listen method or in connection method.

I can run the app with direct values. App working fine with direct values

Here is the listen method error screenshot: console error for the port

CodePudding user response:

Right now you are passing 3000; to the listen function, you need to pass 3000.

Remove the semicolons ; from the env file and it should work.

Have a look at the dotenv npm page here for examples.

Also, you have posted your mongodb credentials online, I'd suggest you change those immediately.

  • Related