Click Below to subscribe

How to Create Multiple Environments In React 2023

In Software development, almost all applications have a need for multiple environments. In this article, we gonna learn how to manage multiple environments in react application.

1. Install env-cmd npm package.

npm i env-cmd

2. Create .env files in the root of your application.

 .env.development
 .env.staging 
 .env.production

.env.development

REACT_APP_API_ENDPOINT=http://localhost:3001

.env.staging

REACT_APP_API_ENDPOINT=http://localhost:3002

.env.production

REACT_APP_API_ENDPOINT=http://localhost:3003

Note:- you need to prefix all environment variables with REACT_APP_

3. Update package.json scripts.

"scripts": {
    "start": "env-cmd -f .env.development react-scripts start",
    "start:staging": "env-cmd -f .env.staging react-scripts start",
    "start:production": "env-cmd -f .env.production react-scripts start",
    "build": "env-cmd -f .env.development react-scripts build",
    "build:staging": "env-cmd -f .env.staging react-scripts build",
    "build:production": "env-cmd -f .env.production react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
},

Syntax:- 

env-cmd -f .env_file command

-f is the alias for --file

4. Finally test your application.

development

npm start
npm build

staging

npm run start:staging
npm run build:staging

production

npm run start:production
npm run build:production

Checkout:- https://github.com/ultimateakash/react-multiple-env

Extras:-

1. You can also use npm_config_ environment variable.

windows

%npm_config_my_variable%

linux/mac

$npm_config_my_variable

2. Now in package.json we can use this variable.

windows

"scripts": {
    "start": "env-cmd -f .env.%npm_config_env% react-scripts start", 
    "build": "env-cmd -f .env.%npm_config_env% react-scripts build", 
    "test": "react-scripts test",
    "eject": "react-scripts eject"
}

linux/mac

"scripts": {
    "start": "env-cmd -f .env.$npm_config_env react-scripts start", 
    "build": "env-cmd -f .env.$npm_config_env react-scripts build", 
    "test": "react-scripts test",
    "eject": "react-scripts eject"
}

3. Now you can pass environment as an argument.

npm start --env=staging
npm build --env=staging

Leave Your Comment