guyforlowbro guyforlowbro - 1 year ago 119
Node.js Question

Best way to get the IP address of client is req.ip or req.connection.remoteAddress?

I'm wondering what the best way to get the IP Address of a client from my express application is, as SOF and docs show

. Not sure what the difference is and which is the one I should use.

Answer Source

req.ip will try to resolve the actual client IP-address by also taking into account headers that are set by proxy servers indicating the origin (client) of the request (although this will only be done if the trust proxy setting is explicitly enabled).

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.

If you're using a reverse proxy that is forwarding requests to your Express server, req.ip and enabling trust proxy is the best solution. Otherwise, just plain req.ip will still do.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download