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
.env.development
or.env.staging
).
This means if you wanted to produce a build for an arbitrary environment by using use values from .env.staging
or .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 thescripts
section of yourpackage.json
:"build:staging": "env-cmd -f .env.staging npm run build"
- Run
npm run build:staging
. This will build your app, with values from.env.staging
.
By using 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 .env
or .env.production
). 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 react-scripts
.
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.