10

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?
}
1
  • 1
    Try inspecting the req object.
    – Tony
    Commented Jan 26, 2015 at 20:42

2 Answers 2

21

This worked:

req.connection.remoteAddress

0
19

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.

1
  • 1
    x-forwarded-for can contain a chain of forwarding hosts. You should split it on coma separator and get the first (leftmost) IP. Or the first (leftmost) public IP if you need it for geolocation for example. Commented Feb 28, 2020 at 21:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.