Create-react-app managing different environments

This article explores how to build with configuration for a specific target environment.

create-react-app supports an environment variables which we can use  to build with configuration for different environments (e.g. staging, production). I managed them by copying respective environment file on the fly to default .env file on the fly & before running actual build.  Now lets explore the real problem & how i managed that.

I am assuming that you are familier with how CRA(create-react-app) manages environments & dotenv module.

Overview –

 

In CRA NODE_ENV variable will be set by react scripts based on the command you running & environment file will be picked based on that.

Like as below (priority left to right) –

npm start:   .env.development.local, .env.development, .env.local, .env

npm run build:   .env.production.local, .env.production, .env.local, .env

npm test:   .env.test.local, .env.test, .env (note .env.local is missing)

 

Our requirements –

 

In my case i have to manage one additional environment(you may want more) which is staging

So here is my final environments list –

  1. local – For local development
  2. staging – Staging server
  3. live – Actual production server

For local, staging & live i have to use different API end points for data, assets path..etc like

  • for local/development
REACT_APP_API_ENDPOINT = 'http://127.0.0.1'
REACT_APP_ASSET_SERVER = 'http://127.0.0.1'
  • for staging
REACT_APP_API_ENDPOINT = 'https://staging-api.com'
REACT_APP_ASSET_SERVER = 'https://staging.com'
  • for live/production
REACT_APP_API_ENDPOINT = 'https://live-api.com'
REACT_APP_ASSET_SERVER = 'https://live.com'

So i have 4 files as –
.env – Default set to empty
.env.development – For local development
.env.staging – for staging server
.env.production – for live server

 

 

The real problem

 

How we can manage staging  environment ?

And my solution is –

COPY RESPECTIVE ENVIRONMENT FILE INTO DEFAULT ENVIRONMENT FILE BEFORE RUNNING BUILD.

 

That is to build for staging copy .env.staging into .env before actual build.

so here is my scripts in package.json


"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "build:staging": "cp ./.env.staging ./.env && npm run build"
}

AND to build for staging run command –

$ npm run build:staging

 

Note that –

  1. On local i am running npm run start
  2. For staging i am running npm run build:staging
  3. For live i am running npm run build
  4. Default .env is set to empty so that i can use it on the fly.

 

Final thoughts –

 

This is how i managed multiple environments by copying different .env files on the fly.  There are multiple other ways like adding temporary  environment variables In Your Shell as suggested by Drew Goodwin in his article.

Its complete your choice.

I hope this article will help you. Thank you so much for your time.

 

Advertisements