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:


JS file:

module.exports.Config = {
  port: process.env.PORT,
  mongoURI: process.env.MONGO_URI,
  mongodbname: process.env.MONGO_DBNAME


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.

Leave a Reply