1

I have a .env file in my project located in the same file where server.js does.

But it server.js file does not see this file.
When I test, I always get 'undefined'.

This is my server.js file:

const express = require("express");
const path = require("path");
const chats = require("./data/data");
const connectDB = require("./config/db");

require("dotenv").config();
connectDB();
const app = express();

const PORT = process.env.PORT || 5000;

// test 1
// test1: undefined
//        ^^^^^^^^^
console.log(`test1: ${process.env.PORT}`);

app.get("/", (req, res) => {
  res.send("API is running");
});

app.get("/api/chats/", (req, res) => {
  res.send(chats);
});

app.get("/api/chats/:id", (req, res) => {
  const chat = chats.find((chat) => chat._id === req.params.id);
  res.send(chat);
});

app.listen(PORT, console.log(`Server started on port ${PORT}`));

This is .env:

PORT=5000

Also, this is how the root looks like:

|backend
      |.env
      |server.js

I tried this but did not help.

require("dotenv").config({ path: "path/to/file" });

srmback
  • 31
  • 6
  • Does this answer your question? [dotenv file is not loading environment variables](https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables) – about14sheep Apr 02 '23 at 00:26
  • @about14sheep, thanks for reply. require('dotenv').config({path:__dirname+'/./../../.env'}) this line of code did not help me. may be I am doing something wrong with __dirname. https://i.stack.imgur.com/KK1xI.png – srmback Apr 02 '23 at 00:32
  • because `/./../../.env` is not the relative path to *your* .env file. use the relative path to *your* .env file. that looks to be `./.env` – about14sheep Apr 02 '23 at 00:43

1 Answers1

-1

I found the error.

My project directory was 'chat'.

So I should have put my .env in the root but not in the 'backend' directory.

srmback
  • 31
  • 6