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 req.ip
& req.connection.remoteAddress
. Not sure what the difference is and which is the one I should use.
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.
The easiest way to find your IP address in Node. js is to pull the client IP address from the incoming HTTP request object. If you are running Express in your Node app, this is very easy to do. Access the socket field of the Express request object, and then look up the remoteAddress property of that field.
::ffff: is a subnet prefix for IPv4 (32 bit) addresses that are placed inside an IPv6 (128 bit) space. IPv6 is broken into two parts, the subnet prefix, and the interface suffix. Each one is 64 bits long, or, 4 groups of 4 hexadecimal characters.
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.
best way to get users IP is req.headers['x-forwarded-for'] || req.connection.remoteAddress;
like this var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
because may be you will use middleware (or most common used proxy) servers (like Cloudflare) for security reasons and if you use req.connection.remoteAddress
it will send your middleware servers IP address everytime, but you can use x-forwarded-for header and req.connection.remoteAddress
or req.ip
together.
for more information read about x-forwarded-for http header
EDIT
as mentioned in comments below best practice to use req.ip || req.connection.remoteAddress
; because even if you use app without proxy, in future you can use it with proxy, and with method above you can use your application without changing it.
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