React listens at default port(3000 ) if you create an application with the create-react-app
command.
I created an react application using create-react-app
command.
The project contains package.json
which contains scripts for starting and running an application.
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
}
Sometimes, We need to change the port to a new port number,an unassigned integer which is in always between 0 to 2 power 16 -1, .
This short post covers a how to change the default port in react application
There are multiple ways we can change the default port in react application.
{{ }
Configure Environment variables in react scripts
Environment variables are specific to running machine operating systems. You have to override port environment variables to a new number with this.
For example, In windows, can change the start script as follows.
"scripts": {
"start": "set port=4000 && react-scripts start",
}
It is the way you can environment set port=4000
In Linux/Ubuntu/Mac system
"scripts": {
"start": "export port=4000 && react-scripts start",
}
cross-env npm library to change the port
first, install cross-env using npm command, This only needs dependency
at development dependency
This works on all OS
like Windows, Linux, and Mac machines.
npm install --save-dev cross-env
Once you installed it, please change package.json
as follows.
"scripts": {
"start": "cross-env port=4000 && react-scripts start",
}
Temporarily with the command line you change the default port as follows
npm run start port=4000
Create a .env file in react application
Another easy approach is to create a .env
file in the root of an application
add the port property with value in the .env file
.env file
port=4000
Note, env file contains environment-specific information, please add it to the .gitignore file not to commit to the source repository.
Wrap up
Adding environment variables like port to the existing machine is a better and clean approach. You can change multiple ways to change the default port in react application. You can choose based on your needs.