Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

dotenv exports undefined data

I’m trying to export data from dotenv file, but does not work, I already installed dotenv but still not working

dotenv file:

PORT=3000
MONGO_URI=mongodb+srv://userfg:<password>@cluster0.45m0c4f.mongodb.net/?retryWrites=true&w=majority
MONGO_DBNAME=inventario

JS file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

require('dotenv').config();
module.exports.Config = {
  port: process.env.PORT,
  mongoURI: process.env.MONGO_URI,
  mongodbname: process.env.MONGO_DBNAME
};

console.log(process.env.PORT);

I get undefined when I call process.env.PORT, process.env.MONGO_URI and process.env.MONGO_DBNAME

File structure

>Solution :

Avoid whenever possible to call require('dotenv').config(); directly.
Those variables are meant to be recovered as regular environment variables, in a transparent way.

The script trying to load the envfile is trying it too late, try to either perform the require('dotenv').config(); in the entry point (i.e. the index.js) or, my preferred appoach, as a dynamic require in the node command line:

node -r dotenv/config index.js

Then remove the require('dotenv').config(); altogether.

This approach is even documented in the dotenv project.

Take a look at this sample project if unsure about it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading