I'm having a difficult time finding how to access the IP address of the REST client from a route.
server.get('api/foo', function(req, res, next) {
// How can I access the IP address of the requester from here?
}
After the client establishes a successful connection to the server, the IP address of the client will be printed on the server console.
The easiest way to find your IP address in Node. js is to pull the client IP address from the incoming HTTP request object. If you are running Express in your Node app, this is very easy to do. Access the socket field of the Express request object, and then look up the remoteAddress property of that field.
req. connection. remoteAddress will contain the IP-address of the client making the request, which in case of a proxy server will be the proxy's IP-address and not the one from the client on whose behalf the proxy is forwarding the request.
This worked:
req.connection.remoteAddress
The other answers won't work behind a proxy, you'll get the proxy server address in those cases.
req.headers['x-forwarded-for'] || req.connection.remoteAddress;
Will work behind a proxy if the proxy sets the original IP in x-forwarded-for
header which many do by default and you can add to something like nginx very easily.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With