How to Fix 'Port Already in Use' Error in Express
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.
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
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().
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}`); });
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.