skip to Main Content

I have a rest api in express js. I’m using a express-rate-limiter to limit requests like so.

const limiter = rateLimit({
  windowMs: 60 * 60 * 1000, // 60 minutes
  max: 1000, // limit each IP to 1000 requests per windowMs
});

When I was developing the phone app the rest api was saying:

Too many accounts created from this IP, please try again after an hour

So I added morgan to my app so I can see logs of the requests made to the api.

if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
} else {
  app.use(morgan('combined'));
}

but when I check the logs I get 127.0.0.1for every request instead of user’s ip address.

127.0.0.1 - - [06/Apr/2021:20:52:13 +0000] "GET /api/daily-deals HTTP/1.1" 200 4922 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"

I am using nginx reverse proxy. so I have enabled trust proxy in my app.

But still I’m not getting the current ip. any idea why?

app.set('trust proxy', '127.0.0.1');

app.listen(PORT, '127.0.0.1', (err) => {
  if (err) {
    console.log(err);
  }

  // eslint-disable-next-line
  console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`);
});

2

Answers


  1. Chosen as BEST ANSWER

    When you are using your own reverse proxy you have to put:

    proxy_set_header X-Forwarded-For $remote_addr;
    

    in my nginx configuration: /etc/nginx/sites-available/default

    that fixed the issue


  2. Two conditions must be met.
    As vajad57 showed nginx configuration:

    proxy_set_header X-Forwarded-For $remote_addr;
    

    and with code before using morgan middleware (from this question):

    app.enable("trust proxy");
    

    For me works only that way.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search