Reputation: 6595
I had to add this code to my project that has Express as a back end and React as a front end in order to deploy to Heroku (along with some other adjustments like the heroku-postbuild
field). I am new to Express/Node and read process.env is the Node environment, but what does it mean to just check if it exists/is set to true? I see people use it to set process.env.NODE_ENV
to development or production but am not familiar with this usage.
if (process.env.NODE_ENV) {
app.use(express.static('client/build'));
const path = require('path');
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'));
});
}
Upvotes: 0
Views: 2790
Reputation: 1330
if
condition is there to check if NODE_ENV
has been set or not (e.g., "" will evaluate to false
).
*
inside app.get()
is a wildcard that matches any route a user could type in a browser for this server (i.e., http://localhost/*).
So what it does is that if the NODE_ENV
is set to something (not necessarily dev or production environment), then for any route (or any web page on the site) requested, you are going to send the client/build/index.html
file back - basically render an index (main) page of the website.
This environment variable (i.e., NODE_ENV
) is defined, well, as an environment variable in some computer (e.g., VM somewhere on the cloud like Heroku). On a cloud, it would probably have "production" set as a value. On your laptop, it may not have anything as you are just testing it out, playing with it, etc. But production environment is quite important because this is where users of your app can see and use your app.
According to Express.js docs, "Setting NODE_ENV to “production” makes Express cache view templates; cache CSS files generated from CSS extensions; and generate less verbose error messages." Ref: https://expressjs.com/en/advanced/best-practice-performance.html
My guess is that it sends this index.html
file while on Heroku, and does something else (depending on defined routes) when it is not.
This link may also help: https://dev.to/flippedcoding/difference-between-development-stage-and-production-d0p
P.S. Natalie noted that Heroku sets Node.js applications to use NODE_ENV=production by default since 2015. Ref: https://devcenter.heroku.com/changelog-items/688
Upvotes: 2