I'm working on a Restful API with node.js and hapi.js. I'm trying to log the IP of the clients that request one of my routes.
This is my current code:
function(request, reply){
var ip = request.headers['x-forwarded-for'] || request.connection.remoteAddress;
console.log('IP: ' + ip);
//more code...
}
But ip is undefined when I watch my logs. How can I solve my problem?
Use request.info.remoteAddress
instead of request.connection.remoteAddress
:
var ip = request.headers['x-forwarded-for'] || request.info.remoteAddress;
Here is a refinement of the accepted answer that accounts for the fact that the x-forwarded-for header can be a comma-separated set of multiple IP addresses in the case where the request passes through multiple proxy servers. In such a scenario the client IP will be the leftmost (first) IP address. This code will handle both possible formats of the header:
var xFF = request.headers['x-forwarded-for'];
var ip = xFF ? xFF.split(',')[0] : request.info.remoteAddress;
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