Search code examples
node.jsexpressdotenv

Error: listen EADDRINUSE: address already in use 3000;


I have a .env file in my root directory with PORT = 3000; inside

In my app.js, I am using the .env file to listen to port 3000

require('dotenv').config();

const express = require('express');
const app = express();
const port = process.env.PORT || 4000;

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

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

After trying to run the file, I get the following error

Error: listen EADDRINUSE: address already in use 3000;

I'm on a Mac, so I tried using sudo lsof -i :3000 in the terminal and am asked for my password.

I type in my password and hit Enter but nothing happens.

How can I remove the error? I believe my password is correct. I did get a huge Mac OS update today--could that cause some password related issues?


Solution

  • Changing the app.js file to

    const express = require('express');
    const app = express();
    const port = process.env.PORT || 3000;
    
    require('dotenv').config();
    
    app.get('/', (req, res) => {
      res.send('Hello World!!!');
    });
    
    app.listen(port, () => console.log(`Example app listening on port ${port}!`));
    

    resolves the issue, but PORT in .env is not being read...