2 Ways to Use Custom Port in React (create-react-app)
( 68 Articles)
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:
Note: A custom port should be a number >=0 and < 65536.
Now run your project by executing:
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",
Now you’re good to go.
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:
- 5 Best Open-Source HTTP Request Libraries for React
- React + TypeScript: Re-render a Component on Window Resize
- React: Get the Width & Height of a dynamic Element
- React + TypeScript: Handling onScroll event
- React + TypeScript: Handle onCopy, onCut, and onPaste events
- React + TypeScript: Multiple Select example