2 Ways to Use Custom Port in React (create-react-app)

Last updated on October 7, 2021 A Goodman Loading... Post a comment

By default, a React project created with create-react-app will run on port 3000. However, you can change the port number to another number you like. This article shows you 2 different ways to achieve it.

Using ENV FIle

Create a new file named .env in the root directory of your project and declare your desired port with it:

PORT=1234

Note: A custom port should be a number >=0 and < 65536.

Screenshot:

Now run your project by executing:

npm start

You will see this:

Modifying the Package.json File

Open your package.json file, head to the scripts block, then edit the following line:

"start": "react-scripts start",

If you’re on a Mac, change it to:

"start": "PORT=9999 react-scripts start",

If you’re using Windows, use this:

"start": "set PORT=20000 && react-scripts start",

Screenshot:

Now you’re good to go.

Conclusion

We’ve covered a couple of different approaches to run a React project on a custom port. If you’d like to explore more about modern React and frontend development, take a look at the following articles:

You can also check our React topic page and Next.js topic page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles