I am trying to use an environment variable in a constructor function in Javascript but with no success.After doing some research I found that my issue was similar to this How to make .env variables work inside JS class constructors? but with some few differences. The solution here mentions to use preload
in the dotenv library to preload your variables so they are picked up in the constructor. However, when you read the dotenv
docs, it is recommended to use the library dotenvx
instead
Note: Consider using dotenvx instead of preloading. I am now doing (and recommending) so.
My issue comes up when using dotenvx, I have added it to my scripts and can see that it says the env variables are injected.
I can confirm this because the value of the variable is logged in my entry file app.js
app.post('/start', startRunLimiter, (req, res) => {
console.log(process.env.MAIN_APP_URL); //-> this works
But not picked up in my constructor function in a different file Dashboard.js
constructor() {
super();
console.log(`test` + process.env.MAIN_APP_URL); // -> prints undefined
this.setUrl(process.env.MAIN_APP_URL);
}
How do i get the variables to be picked up in my constructor function?