I'm receiving this error when I start my node application:
ReferenceError: DEV_MAIL_HOST is not defined
The following code works, when I'm specifically defining which env variable to use.
const transport = nodemailer.createTransport({
host: process.env.DEV_MAIL_HOST,
port: process.env.DEV_MAIL_PORT,
auth: {
user: process.env.DEV_MAIL_USER,
pass: process.env.DEV_MAIL_PASSWORD
}
});
However, I'm trying to conditionally inject env variables based on what mode Node starts up in.
const transport = nodemailer.createTransport({
host: process.env.NODE_ENV === "development" ? DEV_MAIL_HOST : LIVE_MAIL_HOST,
port: process.env.NODE_ENV === "development" ? DEV_MAIL_PORT : LIVE_MAIL_PORT,
auth: {
user:
process.env.NODE_ENV === "development" ? DEV_MAIL_USER : LIVE_MAIL_USER,
pass:
process.env.NODE_ENV === "development"
? DEV_MAIL_PASSWORD
: LIVE_MAIL_PASSWORD
}
});
Here's is my package.json, where I define which mode to start in.
}
"scripts": {
"start": "nodemon -e js,graphql -x NODE_ENV=production node src/index.js",
"dev": "nodemon -e js,graphql -x NODE_ENV=development node --inspect src/index.js",
}
}
What am I missing here?
Fixed thanks to @MadWard's comment. I needed to destructure my environment variables.
From both snippets and the error that is shown, you appear to be using variables without declaring them first.
Either use the variables directly by their full name ( process.env.DEV_MAIL_HOST
, etc.), or initialize them at the beginning of your code:
const {
DEV_MAIL_HOST,
DEV_MAIL_PORT,
DEV_MAIL_USER,
DEV_MAIL_PASSWORD,
LIVE_MAIL_HOST,
LIVE_MAIL_PORT,
LIVE_MAIL_USER,
LIVE_MAIL_PASSWORD
} = process.env;
That's not the correct way to declare environment variables. You should declare an environment variable like: MAIL_HOST
.env file should be different for each environment. In dev .env file MAIL_HOST should contain the development URL and in production .env file MAIL_HOST should contain the production URL
You can choose the env file by using dotenv library by using
require('dotenv').config();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.