0
0
ExpressDebug / FixBeginner · 3 min read

How to Fix 'Port Already in Use' Error in Express

The port already in use error in Express happens when another process is using the same port your app tries to listen on. To fix it, either stop the other process or change your Express app to listen on a different port using app.listen(newPort).
🔍

Why This Happens

This error occurs because only one program can use a specific port on your computer at a time. If your Express app tries to use a port that another app or previous instance of your server is already using, it will fail to start.

javascript
import express from 'express';
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(3000, () => {
  console.log('Server running on port 3000');
});

// If you run this code twice without stopping the first, the second will fail
Output
Error: listen EADDRINUSE: address already in use 127.0.0.1:3000
🔧

The Fix

You can fix this by either stopping the process that uses the port or changing your Express app to listen on a different port. To stop the process, find its ID and kill it. To change the port, update the number in app.listen().

javascript
import express from 'express';
const app = express();

const PORT = process.env.PORT || 3001; // Changed port to 3001

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
Output
Server running on port 3001
🛡️

Prevention

To avoid this error in the future, always check if the port is free before starting your server. Use environment variables to set ports dynamically. Also, properly stop your server when done, and consider using tools like nodemon that restart your server safely.

Running lsof -i :3000 (Mac/Linux) or netstat -ano | findstr :3000 (Windows) helps find processes using a port.

⚠️

Related Errors

Other common errors include:

  • ECONNREFUSED: Your app tries to connect to a server that is not running.
  • UnhandledPromiseRejectionWarning: When async code fails without proper error handling.
  • SyntaxError: Mistakes in your code syntax that prevent the server from starting.

Fixes usually involve checking server status, adding error handling, and reviewing code syntax.

Key Takeaways

Only one process can use a port at a time; conflicts cause the error.
Change your Express app's port or stop the conflicting process to fix it.
Use environment variables to manage ports flexibly.
Check running processes with system commands before starting your server.
Properly stop your server to free the port for future use.