How to run react app on a different port
If you have created a React project using create-react-app you will notice that the application will launch on the default 3000
port. But you can change it using environment file or script.
In this article, we will see what are the possible ways to launch react project on a different port.
Way to run react app on a different port
1. Using environment configuration
We prefer to use environment variables saved in .env
file (useful to store sets of variables for different deploy configurations in a convenient and readable form). Don’t forget to add *.env
into .gitignore
if you’re still storing your secrets in .env files.
Create a .env
file at your project root and specify port number there.
1 | PORT=7777 |
2. Using script
If you don’t want to set the environment variable, another option is to modify the scripts part of package.json
.
From:
1 | "start": "react-scripts start" |
To:
Linux (tested on Ubuntu 14.04/16.04) and MacOS (tested by aswin-s on MacOS Sierra 10.12.4):
1 | "start": "PORT=3006 react-scripts start" |
or (may be) more general solution
1 | "start": "export PORT=3006 react-scripts start" |
For windows system
1 | "start": "set PORT=3006 && react-scripts start" |
3. Using package
You can also use the cross-env library to set the port, and it will work on Windows, Linux and Mac.
Run the following command to install cross-env
package in devDependencies.
1 | npm i cross-env -D |
Now, update the start command of the package.json
.
1 | "start": "cross-env PORT=3006 react-scripts start" |
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂