0

I'm creating an express application

I have a main.js file where is imported the app from express

Other called app.js where is defined the middlewares and what routes use

And other files

The import of dotenv is in the app.js, for that, main.js and app.js can reach the process.env variables but I can't do that the other files that are sync with the project get the env variables

What I am missing?

main.js , this work fine

enter image description here

app.js, this also work fine

enter image description here

other files, here start to break enter image description here

Any ideas of what is happening? :C Or how I can set the dotenv as a Global variable for all the project?

Thank you!

Programmer89
  • 145
  • 3
  • 15

1 Answers1

0

You could try moving your .env up a directory to be in the root instead of /src. I think that is where it expects it to be. If you want to have it somewhere else you can set that in the config.

Default: path.resolve(process.cwd(), '.env')

Specify a custom path if your file containing environment variables is located elsewhere.

require('dotenv').config({ path: '/src/.env' })

Zac
  • 12,637
  • 21
  • 74
  • 122
  • Thanks for the answer zac! But the .env is in the root directory :C! – Programmer89 Mar 22 '23 at 21:56
  • Oh oops sorry I misread your screenshot. Hmm that is odd, I will think about it and update if I think of anything. – Zac Mar 22 '23 at 22:10
  • Restart everything if you added those env files later as maybe system doesnt know about them. Could also try defining the path in config to be absolute. – Zac Mar 22 '23 at 22:16
  • Can turn on debug see if it shows path you expect : require('dotenv').config({ debug: true }) Docs talk about this issue and link to : https://stackoverflow.com/questions/42335016/dotenv-file-is-not-loading-environment-variables a lot of good suggestions.. maybe try `require('dotenv').config({ path: require('find-config')('.env') }) ` – Zac Mar 22 '23 at 22:19
  • Zac, thank you agasin for the answer. Tomorrow i will be doing the debug, its late now haha. I found a walkaround for this and it was just to add in the package.json in the script start -r dotenv/config. This way dotenv will charge for all the project itself. Not the idea, but works – Programmer89 Mar 23 '23 at 01:23