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?
If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':
If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.
The headers object has everything you need, just do this:
This worked for me better than the rest. My sites are behind CloudFlare and it seemed to require
cf-connecting-ip
.Didn't test Express behind proxies as it didn't say anything about this
cf-connecting-ip
header.app.set('trust proxy', true)
req.ip
orreq.ips
in the usual wayParticularly for node, the documentation for the http server component, under event connection says:
So, that means
request.connection
is a socket and according to the documentation there is indeed a socket.remoteAddress attribute which according to the documentation is:Under express, the request object is also an instance of the Node http request object, so this approach should still work.
However, under Express.js the request already has two attributes: req.ip and req.ips
It may be worth mentioning that, according to my understanding, the Express
req.ip
is a better approach thanreq.connection.remoteAddress
, sincereq.ip
contains the actual client ip (provided that trusted proxy is enabled in express), whereas the other may contain the proxy's IP address (if there is one).That is the reason why the currently accepted answer suggests:
The
req.headers['x-forwarded-for']
will be the equivalent of expressreq.ip
.In
nginx.conf
file:proxy_set_header X-Real-IP $remote_addr;
In
node.js
server file:var ip = req.headers['x-real-ip'] || req.connection.remoteAddress;
note that express lowercases headers