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?
While the answer from @alessioalex works, there's another way as stated in the Express behind proxies section of Express - guide.
app.enable('trust proxy')
to your express initialization code.req.ip
orreq.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.According to Express behind proxies,
req.ip
has taken into account reverse proxy if you have configuredtrust proxy
properly. Therefore it's better thanreq.connection.remoteAddress
which is obtained from network layer and unaware of proxy.Just use this express middleware https://www.npmjs.com/package/express-ip
You can install the module using
Usage
var ip = req.connection.remoteAddress;
ip = ip.split(':')[3];