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.
Table of Contents
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 must be a number >=0 and < 65536.
Screenshot:
Now run your project by executing the following command:
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 running 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
You can also check our React category page and React Native category page for the latest tutorials and examples.