简体   繁体   中英

javascript: how to detect environment on server side pages

I've inherited a react/javascript app and I'd like to make a small change to export different mailchimp account variables for prod vs test environments, in mailchimp-configuration.js. (These values get imported from src/server/index.js)

I updated mailchimp-configuration.js to check whether process.env.NODE_ENV == 'production'. This works, but it isn't quite right since I can run my local sandbox (or staging) server 'as production', in which case the production account gets used instead of the test one. I need to use something more conclusive that'll know whether we're running in the production environment vs staging or localhost.

An easy solution on the browser pages is to check the url via window.location.href, but unfortunately from mailchimp-configuration.js, window is not defined.

I suppose I could set a global variable somewhere, but that's last-resort stuff. What's a good way to check my environment from the server side?

thanks!

I need to use something more conclusive that'll know whether we're running in the production environment vs staging or localhost.

There is technically no difference between "a nodejs instance running on a computer" and "a nodejs instance running on a computer". The only way to distinguish "your localhost" and "a production server" is to tell the nodejs instance where it runs in, and thats done by process.ENV .

I updated mailchimp-configuration.js to check whether process.env.NODE_ENV == 'production'. This works, but it isn't quite right since I can run my local sandbox (or staging) server 'as production', in which case the production account gets used instead of the test one.

Actually this is the way to go, if you fear that your secret email account gets used by a test server, then that secret should actually go into a secret manager, such as Vault

You could use one of node's native os functions and determine according to a certain value if you are running node locally in dev -> Link

Standard practice is to set an environmental variable to the according environment you're in (production or development).

process.env.NODE_ENV 

perform a check:

if (process.env.NODE_ENV === 'development') {
// do dev stuff
} 
if (process.env.NODE_ENV === 'production') {
//do production stuff
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM