One common question that comes up when working on a local website is related to the behavior of the npm run dev
command. Each time this command is executed, it starts a long-running process that spins up a local development server.
This practice is widely used in web development, and many tools like Astro and Next.js rely on the same command. However, one observation developers make is that each time they run npm run dev
, the localhost port gets incremented. For example, it starts with port 3000, then switches to 3001, and so on. This behavior can be confusing and may prompt the question of how to force the server to always use port 3000.
The reason for this behavior is that the development server doesn’t automatically terminate when you stop it. When you first run npm run dev
, it listens on port 3000:
If you open another terminal and execute npm run dev
again, a new instance of the server will spin up on port 3001:
You now have two instances of the same app running on http://localhost:3000
and http://localhost:3001
. To force the server to always use port 3000, you need to terminate both processes using ctrl-c
in the terminal. This ensures that no process is occupying port 3000, and you won’t see anything in the browser when you attempt to open http://localhost:3000
.
Once you terminate the processes, you can run npm run dev
again, and this time it will automatically start on port 3000 since it’s now available.
Whenever you make changes to your project (e.g., when running npm install
for a package), you first need to terminate the development server with ctrl-c
and then start it again.
By understanding the behavior of npm run dev
and how to ensure it uses port 3000, you can effectively manage your local development environment for your web projects.