Search code examples
javascriptnode.jsdotenv

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:

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 env-file is probably trying it too late, process.env might be already populated when require('dotenv').config(); is called.

    Try to either perform the require('dotenv').config(); in the entry point (i.e. the index.js) or, my preferred approach, 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.