How to determine a user's IP address in node
How can I determine the IP address of a given request from within a controller? For example (in express):
app.post('/get/ip/address', function (req, res) {
// need access to IP address here
})
In your request
object there is a property called socket
, which is a net.Socket
object. The net.Socket
object has a property remoteAddress
, therefore you should be able to get the IP with this call:
request.socket.remoteAddress
(if your node version is below 13, use the deprecated now request.connection.remoteAddress
)
EDIT
As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['x-forwarded-for']
var ip = req.headers['x-forwarded-for'] ||
req.socket.remoteAddress ||
null;
Note that sometimes you can get more than one IP address in req.headers['x-forwarded-for']
. Also, an x-forwarded-for
header will not always be set which may throw an error.
The general format of the field is:
x-forwarded-for: client, proxy1, proxy2, proxy3
where the value is a comma+space separated list of IP addresses, the left-most being the original client, and each successive proxy that passed the request adding the IP address where it received the request from. In this example, the request passed through proxy1
, proxy2
, and then proxy3
. proxy3
appears as remote address of the request.
This is the solution suggested by Arnav Gupta with a fix Martin has suggested below in the comments for cases when x-forwarded-for
is not set :
var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() ||
req.socket.remoteAddress
Suggestion using modern JS:
- processing
x-forwarded-for
only if set, if so, take the first address - other parameters use optional chaining (?.)
const parseIp = (req) =>
req.headers['x-forwarded-for']?.split(',').shift()
|| req.socket?.remoteAddress
console.log(parseIp(req))
// => 127.0.0.1
If using express...
req.ip
I was looking this up then I was like wait, I'm using express. Duh.
You can stay DRY and just use node-ipware that supports both IPv4 and IPv6.
Install:
npm install ipware
In your app.js or middleware:
var getIP = require('ipware')().get_ip;
app.use(function(req, res, next) {
var ipInfo = getIP(req);
console.log(ipInfo);
// { clientIp: '127.0.0.1', clientIpRoutable: false }
next();
});
It will make the best attempt to get the user's IP address or returns 127.0.0.1
to indicate that it could not determine the user's IP address. Take a look at the README file for advanced options.
You can use request-ip, to retrieve a user's ip address. It handles quite a few of the different edge cases, some of which are mentioned in the other answers.
Disclosure: I created this module
Install:
npm install request-ip
In your app:
var requestIp = require('request-ip');
// inside middleware handler
var ipMiddleware = function(req, res, next) {
var clientIp = requestIp.getClientIp(req); // on localhost > 127.0.0.1
next();
};
Hope this helps