Change the default Port for a create-react-app project

avatar

Borislav Hadzhiev

Sat Apr 30 20221 min read

banner

Photo by Yair Mejía

Change the default Port for a create-react-app project #

To change the default port for a create-react-app project, update the start command in your package.json file to specify the port, e.g. "PORT=3456 react-scripts start" on macOS and Linux and "set PORT=3456 && react-scripts start" on Windows.

Here is how to set the PORT for your project if you are on macOS or Linux.

package.json
{ "scripts": { "start": "PORT=3456 react-scripts start", }, }

And here is how to do the same on Windows.

package.json
{ "scripts": { "start": "set PORT=3456 && react-scripts start", }, }
Now when you run the npm start command, your React application will start on port 3456.

Alternatively, you can create a .env file in the root directory (where your package.json file is) of your project.

.env
# 👇️ default port for create-react-app PORT=3456

If you set the PORT environment variable in a .env file you don't have to change your start command.

change default port env file

Alternatively, you can use the cross-env package to set a command in your package.json file that would work on macOS, Linux and Windows.

Open your terminal in your project's root directory and install the package:

shell
# 👇️ with NPM npm install --save-dev cross-env # ---------------------------------------------- # 👇️ with YARN yarn add cross-env --dev

And update the start command in your package.json file.

package.json
{ "scripts": { "start": "cross-env PORT=3456 react-scripts start", } }

change react port cross env

Using the cross-env package to change the default port makes the command work on macOS, Linux and Windows.

Use the search field on my Home Page to filter through my more than 1,000 articles.