DEV Community

Cover image for Handle multiple environments in ReactJs [dev, stag, prod]
Rajesh Royal
Rajesh Royal

Posted on


Handle multiple environments in ReactJs [dev, stag, prod]

Create React App provides out of the box support for the environment variables. Just create a .env file and you are ready to go.

Why we need multiple environments.


When you are doing development in multiple stages you are definitely going to have different different domain names.

For ex. In your local you are using localhost:100/api/getuser and when you deploy it to prod or stag you may need it to be something

So handle this scenarios you can create separate environment file for each environment.

This is one of the usage cases, you may have more reasons to do so.


I was facing the same problem as above that we have different different endpoints and credentials("not really") for staging and production.

To handle this scenario we used separate .env file for the particular environment.

How to Handle it:

🟢 While using create React App.

If you Don't know how to add environment file to React please read below post.

How to use .env file in react js

  1. Install env-cmd package from NPM .
  2. Create 3 .env files in your root directory. [dev.env, stag.env, .env]
  3. Add you environment variables to your files.
  4. Update your package.json scripts as below.


"scripts": {
    "start": "react-scripts start", // will use .env default
    "build": "react-scripts build",
    "postinstall": "husky install",
    "start:dev": "env-cmd -f dev.env npm start", // use dev.env file
    "build:beta": "env-cmd -f stag.env npm run build", // use stag.env
Enter fullscreen mode Exit fullscreen mode

Now we have three environments for our React app.

  • To run app in dev environment use start:dev cmd.
  • To build and run app in beta use build:stag cmd.
  • To build in production and run use build cmd.

To use these variables write - process.env.REACT_APP_MYVARNAME and It will return the value of current environment variable.

You can add custom variables to your env files to find out in which environment your app is running.

Usage example:
   * // remove the working of console logs
   * // remove any accidental use of console logs
  useEffect(() => {
    if (process.env.NODE_ENV === "production" || 
process.env.REACT_APP_ENV === "STAGING") {
      GlobalDebug(false, false);
    // I know this is a useless comparison 🤣
    if (process.env.REACT_APP_ENV === "DEVELOPMENT" && 
process.env.REACT_APP_ENV !== "STAGING" && 
process.env.REACT_APP_ENV !== "PRODUCTION") {

    getDeviceId().then((uDeviceId) => {
  }, [dispatch]);
Enter fullscreen mode Exit fullscreen mode

References -

comments and improvements are welcome 😀

see you in next post TADA 👋

Top comments (2)

alexkps profile image

Thanks! A very useful article for a beginner programmer

robertommm profile image


Visualizing Promises and Async/Await 🤯

async await

☝️ Check out this all-time classic DEV post