Create React App Build for Multiple Environments (Override NODE_ENV)
If you are using Create React App (CRA), the
npm run build command that calls
react-scripts build (specified in
package.json) makes a “production build” with
NODE_ENV always set to
'production'. If you look at the
build source here, you’ll find the following:
process.env.NODE_ENV = 'production';
This is done to prevent developers from accidentally deploying a build meant for development (or staging) to production that can have issues like:
- Slower/non-optimized builds.
- Using non-production environment values (from
This means if you wanted to produce a build for an arbitrary environment by using use values from
.env.development, then something like
NODE_ENV=staging npm run build would just not work. So overriding
NODE_ENV is not possible.
Although there is a neat way to get around this, let’s see how:
- Install the env-cmd package.
npm install env-cmd --save
- Assuming you want to use environment variables from
.env.staging, add the following to the
scriptssection of your
"build:staging": "env-cmd -f .env.staging npm run build"
npm run build:staging. This will build your app, with values from
env-cmd, we ensure that all the values from
.env.staging gets populated in Node’s environment (
process.env) which won’t be overwritten with values from other files (like
react-scripts internally uses dotenv for config management whose default behaviour is to not override/modify any environment variables that have already been set – which is what we do with
env-cmd above even before
npm run build triggers
Important Note: In the example above, variables from
.env.production that do not exist in
.env.staging will still be used as a fallback. This is because of the
NODE_ENV hard coding described above.