ArslArsl ArslArsl - 1 month ago 7
Node.js Question

difference between request.ip and request.headers['x-forwarded-for']

I want to get ip of the client. I run my node app(express) with this:

var ip = request.ip


Also I saw that it's possible to do like that(which doesn't work when I run my script on localhost):

var ip = request.headers['x-forwarded-for']


What the (result) difference between them?

Answer

Normally the 'x-forwarded-for' is set when the request pass through an HTTP proxy or load balancer. This field contains identifies the node making the request to the proxy. You can see the IETF RFC 7239.

  • "by" identifies the user-agent facing interface of the proxy.

  • "for" identifies the node making the request to the proxy.

  • "host" is the host request header field as received by the proxy.

  • "proto" indicates what protocol was used to make the request.

The request.ip is derived from the left-most entry in the X-Forwarded-For, so its the original ip address of the request. Express doc.