Change the Default Port 3000 in React JS

In react on 3~5 minutes
Change the Default Port 3000 in React JS

By default, React JS applications created with the create-react-app command runs on port 3000. But sometimes this port 3000 might be already used by another application or service. Under that kind of situation, we need to free port 3000 otherwise, we need to change the default port used by React JS.

There are several methods exist to change the default port 3000 of React JS applications. To demonstrate them, first, let’s create a sample React JS application. Open a new terminal window and run the following command. It can take a few minutes to download all the required files and complete the installation process of the React JS application. If you had Internet connection problems during the installation process, you might need to read how to fix NPM timeout issues article.

npx create-react-app react-port-change

Once the installation process is completed, go to React JS project directory using the cd command.

cd react-port-change

As explained earlier, there are a couple of methods that exist to change the default port 3000 of React JS applications.

Change The Default React JS Port With package.json

Open the package.json file with your IDE or text editor. The initial and unchanged package.json file should be similar to the following.

ReactJS package.json

Now take a look at the "scripts" section, we need to change the line that starts with "start". If you are using any Linux or MacOS computer, change that line to either one of these.

"start": "PORT=3001 react-scripts start"

or

"start": "export PORT=3001 react-scripts start"

If you are using Windows, you may use the following line.

"start”: "SET PORT=3001 && react-scripts start”

Now try to start the React JS application with the npm start command, it should start the application with the specified port. In this case, port 3001.

npm start

Change The Default React JS Port With .env

There can be situations where you are not encouraged to change the start script of the React JS application as it might be a problem that might be only related to you. For example, you might be using another application or service which uses port 3000, but all other team members might not use that port. Under that kind of situation, you can use a .env file to achieve the same thing without changing the package.json file.

By default, the create-react-app does not create this .env file. So you need to manually create it at the root directory of the project.

Then mention the required port number like this in the .env file.

PORT=3001

You might also consider mentioning the newly created .env file name in the .gitignore file as it is not required to be in the Git repository you might be using.

gitignore dot env

Next time when you start the React JS application, you should be able to see the newly assigned port number in the terminal window.

React JS new custom port

Share: