DEV Community

Prabir Biswas
Prabir Biswas

Posted on • Edited on

HANDLE MULTIPLE ENVIRONMENTS IN REACT JS

We need multiple environment for different environments. by following method we can provide specific URL to specific development environment.

Create new React app

npx create-react-app envtest
Enter fullscreen mode Exit fullscreen mode

Open the react project in the IDE

Install the dependency env-cmd

npm i env-cmd
Enter fullscreen mode Exit fullscreen mode

Create env files in the root folder of the project
.env
.env-local
.env-prod

Note: you can make development environments, like QA or DEV, depending on your requirements.

Image description

In .env, Add the project name as,

REACT_APP_NAME = APPNAME
Enter fullscreen mode Exit fullscreen mode

Image description

In env-local and env-prod, add the respective environment URL as,

REACT_APP_ENV = respective env name
REACT_APP_API_URL = respective URL
Enter fullscreen mode Exit fullscreen mode

Image description

Image description

Modify the package.json
In Script object,
Remove the start line and add new start script:

Image description

For start,
Local

“start:local” : “env-cmd -f .env-local  react-script  start”
Enter fullscreen mode Exit fullscreen mode

Production

“start:prod” : “env-cmd -f .env-prod react-script start
Enter fullscreen mode Exit fullscreen mode

Image description

Similarly for build,

Local

“build:local” : “env-cmd -f .env-local react-script build”
Enter fullscreen mode Exit fullscreen mode

Production

“build:Prod” : “env-cmd -f .env-prod react-script build”
Enter fullscreen mode Exit fullscreen mode

Image description

Now you can access the URL string, env name from the App.js or any other components where do you want.

Image description

To run the project,

Run in Local:

npm run start:local
Enter fullscreen mode Exit fullscreen mode

Run in Production:

npm run start:prod
Enter fullscreen mode Exit fullscreen mode

Image description

Additional Note:

To build the project,
Build for Local:

npm run build:local
Enter fullscreen mode Exit fullscreen mode

Build for Production:

npm run build:prod
Enter fullscreen mode Exit fullscreen mode

To Test the build,

We have to Install Serve :
To install Serve,

npm install -g serve
Enter fullscreen mode Exit fullscreen mode

To start the build,

Serve -s build
Enter fullscreen mode Exit fullscreen mode

Thanks For Reading

If you found this blog useful, Please like the blog.

Want to connect? Reach me on Linkedin

Wanna see my work? Look into Github

Top comments (0)