How to set NODE_ENV from package.json for react

Mithun Shreevatsa picture Mithun Shreevatsa · Jul 31, 2019 · Viewed 25k times · Source

I am trying to target multiple environments from local while executing react app.

1. Development
2. Staging
3. Production

I am also trying to test for offline mode in any of the environments. So, the scripts what I have configured is as follows:

    "staging-server": "nodemon server.js --environment=staging",
    "staging": "concurrently -k  \"npm:staging-server\" \"NODE_ENV='staging' PORT=3003 react-scripts start\"",
    "prod": "npm run build && forever server.js --environment=production"

I am able to fetch environment arg using args inside my express, but my local ui app is still showing development only when I console for process.env.NODE_ENV. I am also trying to set NODE_ENV with same line for staging, but still no luck. PORT setting is working but, the app is running in 3000 and 3003 both ports. How to get rid off this and help me understand the staging configuration as well by providing useful links or code is fine

Answer

Mithun Shreevatsa picture Mithun Shreevatsa · Jul 31, 2019

As per the docs, we cannot override NODE_ENV, but there is a room to create our own custom variables starting with REACT_APP_. So i configured to look as below:

Reference: https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

"staging": "concurrently -k  \"npm:staging-server\" \"cross-env REACT_APP_ENVIRONMENT='staging' PORT=3003 react-scripts start\"",

And inside my UI application, I can fetch its value by consoling it like this: console.log('REACT_APP_ENVIRONMENT => ', process.env.REACT_APP_ENVIRONMENT);