1

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

1
  • Can you show what's within the env file, and your package.json? Commented Jul 24, 2022 at 15:36

3 Answers 3

4

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"});
Sign up to request clarification or add additional context in comments.

5 Comments

Still have the same error.
Did you install the dotenv package? Can I see the package.json file?
{ "name": "back-end", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "body-parser": "^1.20.0", "cors": "^2.8.5", "dotenv": "^16.0.1", "express": "^4.18.1", "mongoose": "^6.4.6", "nodemon": "^2.0.19" } }
If I replaced the env file with a new place according to the second picture It worked. But I want to move that file to the back-end folder. Then how should change my path?
Oh I misunderstood the .env file's path.. I thought it was in the main folder. In that case, you can change the path to "./back-end/.env"
2

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

3 Comments

Thank you I have followed these steps. But didn't work
Go into back-end folder and then run node server.js instead of node back-end/server.js
Or if you wants to run node back-end/server.js then you have to specify .env path
1

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);

2 Comments

I have installed dotenv
If I replaced the env file with a new place according to the second picture It worked. But I want to move that file to the back-end folder. Then how should change my path?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.