How to Change The Default Port in A Create-React-App Project

Avatar photo

By George

2 min read
Bookmark this post

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

package.json
 "scripts": {
    "start": "PORT=3001 react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
JSON5

Using 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 
Bash

Keep 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
Bash

Now open your .env file and type

.env
PORT=3001
Plaintext

According 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! 😎

DigitalOcean Referral Badge
guest
0 Comments
Inline Feedbacks
View all comments

Continue reading

Quick Guides

How to Add Sass to A Create-React-App Project

Quick Guides

Do You Still Need To Use npm install –save?

Subscribe to our newsletter

Dive into the Fun Side of Tech! Posts, News, and More Delivered to Your Inbox!

Intuit Mailchimp