Fix EADDRINUSE Port Already in Use Error in Node.js
EADDRINUSE error happens when your Node.js app tries to use a port that another process is already using. To fix it, either stop the other process using that port or change your app to listen on a different free port.Why This Happens
This error occurs because your Node.js server tries to listen on a port that is already taken by another program or another instance of your app. Ports are like doors for your computer to communicate over the network, and only one program can use a door at a time.
const http = require('http'); const server = http.createServer((req, res) => { res.end('Hello World'); }); server.listen(3000, () => { console.log('Server running on port 3000'); }); // Running this code twice without stopping the first will cause EADDRINUSE error
The Fix
To fix this error, you can either stop the process that is using the port or change your Node.js app to listen on a different port that is free. You can also add error handling to detect this problem and respond gracefully.
const http = require('http'); const PORT = 3001; // Changed port to avoid conflict const server = http.createServer((req, res) => { res.end('Hello World'); }); server.listen(PORT, () => { console.log(`Server running on port ${PORT}`); }); server.on('error', (err) => { if (err.code === 'EADDRINUSE') { console.error(`Port ${PORT} is already in use. Please use a different port.`); } else { console.error(err); } });
Prevention
To avoid this error in the future, always check if the port is free before starting your server. Use tools like lsof or netstat to find processes using ports. Also, consider using environment variables to set ports dynamically and add error handling in your code to catch port conflicts early.
- Use
process.env.PORTto allow flexible port assignment. - Stop previous server instances before restarting.
- Use scripts or tools to kill processes blocking ports.
Related Errors
Other common network errors include:
- ECONNREFUSED: When your app tries to connect to a server that is not running.
- ETIMEDOUT: When a connection attempt takes too long and times out.
- EACCES: When your app lacks permission to use a port (usually ports below 1024).
Fixes usually involve checking server status, permissions, and network settings.