0

I want to use environment variables in my NodeJS server,

But to connect to my cloud mongoDB database, I used environment variables that are equals to undefined,

Here's a part of the code :

require("dotenv").config();

console.log(process.env.USER); <------ output: undefined
console.log(process.env.PASSWORD); <------ output: undefined

mongoose
  .connect(
    `mongodb+srv://${process.env.USER}:${process.env.PASSWORD}@ofilms-demo-f9iwz.mongodb.net/test`,
    { useNewUrlParser: true, useUnifiedTopology: true }
  )

Here's my .env file at the root of the server :

USER=user
PASSWORD=password

but the process.env.USER and process.env.PASSWORD are undefined, when I console log them,

Did i miss something ?

Thanks,

6
  • Can you share the folder structure? I guess something is fishy in the location of the file. Commented Dec 29, 2019 at 13:42
  • 1
    make sure .env file is at the root. also see what is the output of const result = dotenv.config() Commented Dec 29, 2019 at 13:42
  • make sure you are using require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' }) if the path of your env variables is not at root and is not .env Commented Dec 29, 2019 at 13:46
  • wow it's because th env filr wasn't exactly at the root, it was 1 level inside, so sorry Commented Dec 29, 2019 at 13:47
  • @Versifiction glad it is resolved now. Commented Dec 29, 2019 at 13:48

1 Answer 1

1

make sure .env file is at the root. also see what is the output of const result = dotenv.config()

Also, make sure you are using require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' }) if the path of your env variables is not at root and is not .env

Sign up to request clarification or add additional context in comments.

Comments

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.