So you just generated a new cool side project and now you are wondering how one changes the default port in a create-react-app project. After all, we have other ports available, right? And there could be a case that 3000
port is already taken. But how can you do that? There are several ways to do that, so let’s check the basic ones.
Using package.json
One way is to go to your package.json
file and change your port through your scripts options, in this case, we are adding PORT=3001
to denote that we want our app to run in port 3001
"scripts": {
"start": "PORT=3001 react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
JSON5Using the command line
In certain scenarios, you may find it necessary to specify the port directly via the command line when executing your run command. You could do that by typing in your terminal
PORT=3001 npm start
BashKeep in mind that if you have a port defined on your package.json and you try adding it inline through the terminal, your package.json port setting will override any port passed through the terminal.
Using .env file
In case you are working on a more complex project or a project that you will be deploying for the world to see your awesome work, you’ll need to set the port to a dynamic value. Why is that? Because the system that will handle your deployment will also be handling the ports.
In this case, you just need to tell your app, where to find the port’s value that will be used, when deployed.
Let’s start by creating a file called .env
. Type in your terminal
touch .env
BashNow open your .env
file and type
PORT=3001
PlaintextAccording to the advanced configuration documentation, of Create-React-App, the app’s listening port is determined by reading the value of PORT from the .env
file by default.
As a result, our application will utilize the PORT value specified in the .env
file to run, so there is no need to make any more changes to our code.
If you’re curious about the order of precedence in case someone adds a port to every possible option, I’ve conducted experiments that reveal the following respected order.
package.json
- command line
.env
file
Don’t forget to have fun with your new project!! You got this! 😎