Express.js: how to get remote client address


I don't completely understand how I should get a remote user IP address.

Let's say I have a simple request route such as:

app.get(/, function (req, res){
   var forwardedIpsStr = req.header('x-forwarded-for');
   var IP = '';

   if (forwardedIpsStr) {
      IP = forwardedIps = forwardedIpsStr.split(',')[0];  

Is the above approach correct to get the real user IP address or is there a better way? And what about proxies?

7/23/2017 1:32:38 PM

Accepted Answer

If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.

7/4/2013 3:29:31 PM

While the answer from @alessioalex works, there's another way as stated in the Express behind proxies section of Express - guide.

  1. Add app.enable('trust proxy') to your express initialization code.
  2. When you want to get the ip of the remote client, use req.ip or req.ips in the usual way (as if there isn't a reverse proxy)

More options for 'trust proxy' are available if you need something more sophisticated than trusting everything passed through in x-forwarded-for header, and your proxy doesn't remove preexisting x-forwarded-for header from untrusted sources. See the linked guide for more details.

NOTE: req.connection.remoteAddress won't work with my solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow