In my work, there are environment variables predefined by the DevOps team which must obey certain company-wide rules. The implication: no custom prefixes, such as the
REACT_APP_ , are allowed as a part of environment variable names.
The particular use case this time is to get my client app go through the CI build process having
NODE_ENV=staging, so that our business users can see a visual marker of “staging” when testing and rest assured that their test operations won’t mess up the real data.
This made me revisit the way of passing environment variables to the build process since my client app was scaffolded with the Create React App. As it turns out, there are three hurdles to cross if you want to build a CRA with a
NODE_ENV other than “development” and “production”.
1. Pass Through the Real NODE_ENV to the build process
According to the official documentation,
NODE_ENV is ready to be consumed during build time. However, it took me some digging to find out why our DevOps’
NODE_ENV=staging kept ending up as
production in the built app:
Create React App’s build script has a line hard coded
NODE_ENV = 'production'.
Since I’ve already ejected because I needed to tweak other Webpack settings, I went on to change this:
2. Change the webpack config to allow for an optimized build for staging
CRA build script uses the webpack config defined in
config/webpack.config.prod.js Since it does not expect a
NODE_ENV other than “production” here, it throws an error if it sees one. So this is where I also need to change to squeeze the “staging” in:
3. Pass through the NODE_ENV to the react app
CRA injects the hard-coded
NODE_ENV (in webpack.config.dev.js and webpack.config.prod.js), and any other environment variables starting with
process.env. , just like in a Node app.
However, any other variables in the environment, including the real
NODE_ENV , are stripped off from this
The quick and dirty remedy is to cheat. This is how I sneaked
NODE_ENV in the testing regex (sorry):
Actually, the particular use case “to support staging build” has already been discussed in the CRA github repo. However, two years later it still remains a “issue: proposal”, so people with the same issue have to come up with their own remedy.
Fortunately, CRA is extremely well documented. Whether you just want to do a quick hack or find a proper way to tweak something elegantly, it is open to all possibilities.