Mz_22
Mz_22

Reputation: 53

Node.js Express custom process.env variables not accessible from all files

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!!

Upvotes: 2

Views: 4688

Answers (3)

Raybi
Raybi

Reputation: 41

Just 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!

Upvotes: 4

nick
nick

Reputation: 1

The dotenv.config() should come before importing the routes in the index.js

Upvotes: 0

TBA
TBA

Reputation: 1074

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.

Upvotes: 2

Related Questions