DEV Community

Shubham
Shubham

Posted on

How to Handle Multiple Environments in a React App

Use Case

While developing a web application most of the developers use Create React App. This means that once you start creating a build, it gets created for a specific environment and continues to exist in the same environment.

"scripts": {
    "start": "node scripts/start.js",
    "build": "node scripts/build.js",
    "test": "node scripts/test.js"
  }
Enter fullscreen mode Exit fullscreen mode

Developers can only use two environments by default.

  • Development — NODE_ENV=development when developing the application locally. Uses .env.development by default, if available.

  • Production — NODE_ENV=production when building the application for deployment. Uses .env.production by default, if available.

Imagine my project has four environments:

  • Development
  • Testing
  • Staging
  • Production

Suppose you have different API URL for each environment or APPINSIGHTS_KEY which can used for the analytics. You can add the configuration in the .env file. Below are the files which we can used for different environments.

.env.development
REACT_APP_BASE_API_URL = 'https://learning.int.org/'

.env.qa
REACT_APP_BASE_API_URL = 'https://learning.qa.org/'

.env.candidate
REACT_APP_BASE_API_URL = 'https://learning.candidate.org/'

.env.production
REACT_APP_BASE_API_URL = 'https://learning.production.org/'

Note: Prefix “REACT_APP_” is required for creating custom variables in React.

Now we need to change the build script in package.json file.

"scripts": {
    "start-js": "run-s react:start lint",
    "react:start": "react-scripts start",
    "start:development": "env-cmd -f .env.development npm run-script start-js",
    "build:integration": "env-cmd -f .env.integration npm run-script build",
    "build:qa": "env-cmd -f .env.qa npm run-script build",
    "build:candidate": "env-cmd -f .env.candidate npm run-script build",
    "build:production": "env-cmd -f .env.production npm run-script build",
    "build": "set \"GENERATE_SOURCEMAP=false\" && rimraf ./build && react-scripts build",
  }
Enter fullscreen mode Exit fullscreen mode

Access the variables in-app : process.env.REACT_APP_BASE_API_URL

Note: Though we have added four different environments and when you build the app NODE_ENV will be production. To distinguish the builds, you can add REACT_APP_ENV and specify your environment there.

Hope this article solves some of the problems that occur on day to day basis.

Discussion (2)

Collapse
twocs profile image
Tom Anderson

What's env-cmd? Not mentioned in the article above but it looks like it's a third-party npm package. npmjs.com/package/env-cmd

Collapse
shubhamagarwal profile image
Shubham Author

Hi Tom,
It's a NPM package.
npmjs.com/package/env-cmd