Logo

How to specify a port to run a create-react-app based project?

When you use Create React App to scaffold a React project, the local development server typically runs on port 3000 by default. If you need to run it on a different port—perhaps because 3000 is already in use—you can do so using environment variables.

1. Using the Environment Variable Directly

You can set the PORT environment variable when running the start script. For example, if you want to run your app on port 3001:

On macOS/Linux:

PORT=3001 npm start

Or if you’re using yarn:

PORT=3001 yarn start

On Windows (cmd.exe):

set PORT=3001 && npm start

(In PowerShell, you’d use $env:PORT=3001; npm start.)

2. Using a .env File

Create React App also respects a local .env file at the root of your project. If you want to avoid setting environment variables in your terminal each time, place a line in a .env file:

PORT=3001

Then run:

npm start

or

yarn start

Create React App will automatically pick up PORT=3001 from the .env file and start the server on port 3001.

3. Best Practices and Tips

  1. Keep Environment Variables Out of Version Control
    Typically, .env files contain settings specific to each environment (development, test, production). Consider adding .env to your .gitignore if it contains sensitive information—though port numbers alone aren’t sensitive, other secrets might be.

  2. Avoid Conflicting Ports
    Always ensure the chosen port is not already used by another service. If needed, you can choose from the ephemeral port range (49152–65535) to minimize conflicts.

  3. Check Your .env.* Files
    Create React App also supports multiple environments with .env.development, .env.production, etc. Make sure you’re setting the port in the correct file for your use case.

With these steps, you can easily change the port for a Create React App project to better suit your local environment or avoid conflicts with other processes. Happy coding!

CONTRIBUTOR
TechGrind