Environment: Node.js, dotenv
require('dotenv').config()
is typically only required in the main file such as app.js. With that one call process.env
can be referenced in every file in the app. This answer agrees with that, https://stackoverflow.com/a/58697426/12582054
However I just ran across an instance where I get an error if I don't include require('dotenv').config()
in an additional file and I'm not sure why.
Simplified Example:
app.js
const path = require('path');
// Custom path to .env file.
require('dotenv').config({ path: path.join(__dirname, '/models/.env')});
const middlewareFile = require('./controllers/middleware-file');
middleware-file.js
const USPS = require('usps-webtools-promise').default;
const usps = new USPS({
userId: process.env.USPS_USER_ID,
properCase: Boolean
});
usps-webtools-promise appears to be the module triggering the error.
If I don't include the dotenv reference at the top of middleware-file.js the USPS module throws an error. It points exactly at the first letter of the value process.env.USPS_USER_ID
.
throw new error_1.default("Must pass USPS userId");
USPSError [USPS Webtools Error]: Must pass USPS userId
at Object. (c:\website\controllers\middleware-file.js:35:14)
I can solve the error by adding dotenv to the top of the file.
const path = require('path');
require('dotenv').config({ path: path.join(__dirname, '../models/.env')});