Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knowing request IP in Hapi.js Restful API

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?

like image 957
Leo Avatar asked Dec 25 '22 21:12

Leo


2 Answers

Use request.info.remoteAddress instead of request.connection.remoteAddress:

var ip = request.headers['x-forwarded-for'] || request.info.remoteAddress;
like image 118
Gergo Erdosi Avatar answered Jan 08 '23 17:01

Gergo Erdosi


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;
like image 27
QuarkleMotion Avatar answered Jan 08 '23 17:01

QuarkleMotion