How to Fix EADDRINUSE Error in Node.js
The EADDRINUSE (Address Already In Use) error occurs when Node.js tries to bind to a port that is already occupied by another process. Here is how to fix it.
Find and Kill the Process on Windows
Open PowerShell as administrator. Find the process using port 3000: netstat -ano | findstr :3000. Note the PID. Kill it: taskkill /PID
Use an Environment Variable for the Port
Instead of hardcoding the port, use process.env.PORT || 3000. This lets you set a different port without changing code. Run: set PORT=3001 && node server.js (Windows) or PORT=3001 node server.js (Mac/Linux). Many hosting platforms set the PORT variable automatically.
Gracefully Handle Port Conflicts
Use server.on('error') to handle the EADDRINUSE error and try a different port: server.on('error', (err) => { if (err.code === 'EADDRINUSE') { server.listen(0); /* picks random port */ } }). This lets your app fall back to an available port automatically.
Prevent EADDRINUSE in Development
Use nodemon with its -L flag for automatic restarts. Use concurrently to manage multiple processes. Ensure your editor's integrated terminal is not running a duplicate server. Use the --watch flag to restart only on file changes.
Check Port Availability in Code
Use the portfinder npm package to find an available port automatically: portfinder.getPortPromise().then(port => { app.listen(port); }). This is useful for testing and CI environments where port availability varies.