How to change the default port for your react app
There are several ways to change the default port for your react application, Let us start with the easy one.
Change the port from your .env file
You can create a .env file and just add the port number you want to use. Like this
PORT=4000
// .env file
PORT=4000
Once you set it, you can start your react application. React will automatically start the application using the PORT number you specified.
Changing the port from your package.json
You can also change your port number from your package.json file. Let us see how.
Add PORT=3456
to the value of start on MacOS and set PORT=4000
to the value of start on Windows.
On macOS
"scripts": {
"start": "port=4000 react-scripts start",
},
On Windows
"scripts": {
"start": "set port=4000 && react-scripts start",
},
Changing the PORT number from the Terminal or CMD
Using this method, you are changing the port number using your OS's environmental variable.
// Using cmd
set PORT=4000
// using terminal, or bash
export PORT=4000
// using powershell
$env:PORT=4000
After running this on your terminal or cmd, run npm start
to start the project
Using the cross-env package
The cross-env package can also change your port number to a custom port. First, to be able to change our port number using this package, we will have to install, it.
On your terminal or command prompt, run npm install cross-env
Once it is installed add cross-env PORT=4000 to the value of start in your package.json
"scripts": {
"start": "cross-env PORT=4000 react-scripts start",
},
After doing any of the above methods, your react app should be available on localhost:4000