I am working on an app with Node.js and express and am using the 'dotenv' package to config/load my variables from the .env file. My issue is that I can only access the variables I defined in the main index.js file and not in all of the project files. I would like to be able to do so to do stuff like set up the db config in a separate file.
database=application`
And this is what I have in index.js
:
`const dotenv = require('dotenv');
dotenv.config({ path: './config/config.env' }) const HOSTNAME = process.env.HOST || 'localhost'; const PORT = process.env.PORT || 3000;`
As I said, I have no issue accessing these variables in the index.js
file but if I try to access process.env.DB_SERVER
for example from a different file, the value is undefined.
Any help or suggestions would be much appreciated! Thanks!!
I am working on an app with Node.js and express and am using the 'dotenv' package to config/load my variables from the .env file. My issue is that I can only access the variables I defined in the main index.js file and not in all of the project files. I would like to be able to do so to do stuff like set up the db config in a separate file.
database=application`
And this is what I have in index.js
:
`const dotenv = require('dotenv');
dotenv.config({ path: './config/config.env' }) const HOSTNAME = process.env.HOST || 'localhost'; const PORT = process.env.PORT || 3000;`
As I said, I have no issue accessing these variables in the index.js
file but if I try to access process.env.DB_SERVER
for example from a different file, the value is undefined.
Any help or suggestions would be much appreciated! Thanks!!
Share Improve this question asked Jan 12, 2023 at 14:08 Mz_22Mz_22 531 silver badge4 bronze badges 1- Are you configure dotenv before trying to read env variables in your other files? – TBA Commented Jan 12, 2023 at 14:24
3 Answers
Reset to default 4Just keep
import dotenv from 'dotenv'; or const dotenv = require('dotenv');
dotenv.config();
At the top of your server.ts/js or index.ts/js file and it'll work!
Note that all imports modules in your index.js
file are evaluated before index.js is being evaluated.
This means that dotenv.config({ path: 'config/config.env' });
is being executed only after other imported were executed, so inside those modules the DB_SERVER environment variable is not yet loaded.
The dotenv.config()
should e before importing the routes in the index.js