最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js Express custom process.env variables not accessible from all files - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 4

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!

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

发布评论

评论列表(0)

  1. 暂无评论