I have a react/node app that I\'m deploying. One of the components attempts to access NODE_ENV in order to determine which host URL to use (localhost or heroku).
I now r
One of the components attempts to access NODE_ENV in order to determine which host URL to use (localhost or heroku).
Yup, absolutely!
There's a difference here between having stuff around at build time, and at runtime. You'll have NODE_ENV
around at buildtime - say you run webpack
or something to build some JSX, or whatever.
You won't have NODE_ENV
around at runtime, when the user visits your site. There's no concept of environmental variables in that web browsing context.
What I've done in this case is to programmatically create a file that will conditionally have the web server URL. Or even captures the NODE_ENV
and puts the value in the application for later.
As a practical example: in a React project I was on a couple years ago we autogenerated our index.html file. This was a silly little file, bringing in our index.html.templ after that file came out the other end of our build pipeline, it would look like this for our production build: index.html Then we just used normal DOM Javascript to grab the body element and check the attribute (then put it in a Redux store? I forget exactly). At user visit time, we have an apparently hard-coded value of "production". But you and I know better! Update: I forgot, there's actually two ways of doing this in Webpack itself, without using an external template tool and generating a file like I describe here! Use the WebPack define plugin. This will essentially add another step to your transpiling phase: one that goes in and replaces a literal string with some other literal string. So There's some environmental variable support in Webpack itself. Apparently if you run webpack with Javascript tags we require and adding a
let e = "NODE_ENV"
would become let e = "production"
. There's a good Medium blog post about defineplugin, and it's kind of cool.webpack --env.NODE_ENV=production
. Then... maybe you can use process.env.NODE_ENV
? The Webpack documentation for this feature isn't exactly clear on this