Is there a way to use environment variable in another directory in a node.js app

Viewed 272

I have a project with folder structure is as follows,

Root > client, server

I want to use the environment variables form the .env file of my Root directory in the /Server/src, But when I try to import it in /Server/src the environment variables are undefined.

Is there a way to use those environment variables in the Server directory?

// from Root directory
const dotenv = require("dotenv");

dotenv.config();

module.exports = {
  NODE_ENV: process.env.NODE_ENV,
}
// from Server directory
const { NODE_ENV,} = require("./config");

console.log(NODE_ENV); //value returns undefined
1 Answers

I see what you're trying to do, but unless the file path is "./config" then it won't work. You said it is in the root directory, so likely you are not using the right path. There will need to be at least one ../ to get back out of the server directory and into the root directory to access the file you're exporting from.

That being said, why bother? You should just require dotenv in any file you need to access the environment variables. I don't know what you're saving by using this method.

Pretty much the same amount of code, but less, since you're not creating this extra layer of abstraction:

// from Server directory
require("dotenv").config();

console.log(process.env.NODE_ENV);
Related