- Published on
How to Change the Default Port Number in React: React Tips
- Authors
- Name
- Name
- Stackademic Blog
- @StackademicHQ
Changing PORT Number in React JS
Introduction 🌟
When diving into React development, one of the first things you might want to customize is the default port number. React applications, created using create-react-app
, typically run on port 3000. However, there might be scenarios where this port is already in use or you need to align with certain deployment environments.
This article will guide you through the process of changing the default port number in React. We'll cover steps for different operating systems, ensuring beginners and seasoned developers alike can follow along easily.
Understanding the Default Setting 🔍
By default, React applications created with create-react-app
are configured to run on port 3000. This setting is embedded in the underlying scripts that start the development server. To customize this, we need to modify the start-up configuration.
Changing the Port Number in Windows 🪟
On Windows, you can change the port number using environment variables. Here's how:
- Open the project folder in your favorite code editor.
- Locate the
package.json
file in the root directory. - In the
scripts
section, you will find a line similar to"start": "react-scripts start"
. - Modify this line to set the
PORT
environment variable. For example, to change the port to 5000, use:
"scripts": {
"start": "set PORT=5000 && react-scripts start"
}
Save the
package.json
file.Run your project using
npm start
. Your React application should now be running onhttp://localhost:5000
.
Changing the Port Number in macOS/Linux 🐧🍏
The process is similar on macOS and Linux, with a slight change in the syntax for setting environment variables. Follow these steps:
- Open your project in a code editor.
- In the
package.json
file, modify thestart
script like this:
"scripts": {
"start": "PORT=5000 react-scripts start"
}
Run npm start
in your terminal. The application will launch on the new port, such as http://localhost:5000
.
Using Environment Configuration Files 📄
Another approach is to use environment-specific configuration files. create-react-app
supports .env
files for setting environment variables. Here's how you can use them:
- In your project root, create a file named
.env
. - Add the following line to set the port:
PORT=5000
Save the file and run npm start
. Your app will start on the specified port.
Conclusion 🎉
Customizing the port number in a React application is straightforward. Whether you're on Windows, macOS, or Linux, you can easily adjust this setting in your package.json
file or by using an .env
file. This flexibility allows for seamless integration with various development and deployment environments. Happy coding!