javascriptnode.jsdotenv

process.env.<variable> not accessible


I have at the top of /src/index.js

import dotenv from "dotenv";
dotenv.config({path:"./.env"});

And this in /cloudinary.js

cloudinary.config({ 
  cloud_name: process.env.CLOUD_NAME, 
  api_key: process.env.CLOUD_API_KEY, 
  api_secret: process.env.CLOUD_API_SECRET,
  secure: true
});

process.env.* is not accessible here. I can't use require(), not even sure it would work. I think the problem is of the directory struture like the calling of dotenv() in /src/index.js and using them in /cloudinary.js

Is there any way to fix this and what exactly is the problem.

One solution is to import it again in cloudinary.js but I don't want to.


Solution

  • Remember that imports are aggregated and executed before code execution happens in the same module, so if your index has an import for your cloudinary file, but "normal code" for running dotenv, you're loading your .env file after you're configuring cloudinary.

    Instead, create a new file, load-env.js with only that dotenv instruction, then import that as the very first import in index.js. Now your dotenv config will run before anything else is allowed to happen, as part of the import resolution, and then by the time the cloudinary module import happens you're working with the correct process.env data.

    However, the real fix (if you're using Node v20 or newer) is to not use dotenv at all. Environment file loading is built into Node itself, so just run node --env-file=.env src/index instead of node src/index and done. This will update process.env before any of your own code runs so there are no timing issues like the ones associated with using dotenv.