What are the steps to resolve Error: listen EADDRINUSE: address already in use in a Node.js server?

Fixing the EADDRINUSE Error in Node.js

The error Error: listen EADDRINUSE: address already in use occurs when the address or port your Node.js server is trying to bind to is already in use. Here are the steps to resolve this issue.

1. Identify the Process Using the Port

First, identify which process is using the port. You can do this by running the following command in your terminal:

lsof -i :[port_number]

Replace [port_number] with the actual port number your server is trying to use. This command will list the process ID (PID) using the port.

2. Terminate the Process

Once you have the PID, terminate the process using:

kill -9 [PID]

Replace [PID] with the actual process ID. This will free up the port.

3. Check for Orphaned Processes

Sometimes, the process might be a zombie or orphaned process. To list all Node.js processes, use:

ps aux | grep node

Identify any unwanted processes and terminate them using the kill -9 command.

4. Use a Different Port

If you don't want to terminate the process or need a quick fix, you can change the port your Node.js server is listening on. Modify your server setup to use a different port:

const PORT = process.env.PORT || 3001;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

5. Handle Port Conflicts Gracefully

To make your application more robust, you can add error handling for port conflicts:

const server = app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

server.on('error', (error) => {
    if (error.code === 'EADDRINUSE') {
        console.error(`Port ${PORT} is already in use.`);
        process.exit(1);
    } else {
        throw error;
    }
});

Additional Resources

For more information on handling this error, you can refer to the following resources: