How to get IP address in Node.js#

Getting a user's IP address seems pretty straightforward in Node.js, right? Does it need a special page on this website? Yes it does, we'll find out why in a few seconds.

Conventional wisdom says, this is how you would get the IP address from a request:

var ip = req.connection.remoteAddress;

But there is a problem. If you are running your app behind Nginx or any proxy, every single IP addresses will be

Probably you can see the problem now. So what is the solution?

Look for the originating IP address in the X-Forwarded-For HTTP header. You will find it in req.header('x-forwarded-for'). Considering that fact, here is the best way to get the IP address of a user:

var ip = req.header('x-forwarded-for') || req.connection.remoteAddress;

Now you can be sure the variable ip will catch the IP address of the client, not your proxy's.