In React projects created with create-react-app, you can specify the runtime port by setting the environment variable PORT. Here are several ways to set this environment variable:
Using Command Line Directly
You can directly set the PORT environment variable in the command line when starting the project. For example, on Unix systems (including macOS and Linux), you can use the following command:
bashPORT=3001 npm start
On Windows, you can use the set command:
bashset PORT=3001 && npm start
If you are using Windows PowerShell, the command is different:
powershell$env:PORT=3001; npm start
Using .env File
create-react-app supports loading environment variables from a .env file in the project root directory. You can create a .env file (if it doesn't exist) and add the following content to specify the port:
shellPORT=3001
Every time you run npm start, create-react-app will load the environment variables from the .env file.
Comprehensive Example
Suppose your project needs to run on port 3001. First, create a .env file in your project root directory (or edit it if it already exists) and add the following content:
shellPORT=3001
After saving the file, every time you run npm start, the React development server will automatically start on port 3001.
If you occasionally need to run on a different port, you can temporarily override the settings in the .env file from the command line, for example:
bashPORT=3002 npm start
This way, even if the .env file specifies port 3001, the application will start on port 3002.
Note: The port must be an unused port number. If the specified port is already in use by another application, the React development server will throw an error indicating that the port is occupied.