VersifiXion
VersifiXion

Reputation: 2292

Using environment variables in NodeJS (with npm package dotenv)

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,

Upvotes: 0

Views: 207

Answers (1)

Ashish Modi
Ashish Modi

Reputation: 7770

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

Upvotes: 1

Related Questions