Nuwan Chamikara
Nuwan Chamikara

Reputation: 896

Node Server .env file undefined in server.js

The below screenshot shows my file structure in VS code. I have used npm concurrent to run both backend and frontend simultaneously. My problem is env file is not recognized in the server file. Please tell me what is wrong here.

enter image description here

Second screenshot for illustration:

enter image description here

Upvotes: 1

Views: 235

Answers (3)

Sahil Thummar
Sahil Thummar

Reputation: 2510

write PORT in .env file in backend folder

PORT = <PORT_NUMBER>

For Ex.

PORT = 3000

Install dotenv in backend folder

npm i dotenv

Import dotenv in server.js file

require('dotenv').config()

or set .env path in

require("dotenv").config({path: "./back-end/.env"});

Then Check by:

console.log(process.env);

Run in backend folder

node server.js

Upvotes: 2

Hoon
Hoon

Reputation: 103

You can specify the path where the .env file is to dotenv package.

Please modify the following line of code to

require("dotenv").config();

like this:

require("dotenv").config({path: "./back-end/.env"});

Upvotes: 4

user14758149
user14758149

Reputation:

To use DotEnv, first install it using the command: npm i dotenv . Then in your app, require and configure the package like this: require('dotenv'). config()

    require('dotenv').config();

console.log(process.env.MY_ENV_VAR);

Upvotes: 1

Related Questions