Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "x-forwarded-for" in Node.js (without Express if possible)

For my current project, I need to get the remote IP address in a Node.js http.createServer((req,res)=>{}); function. I've tried looking through the API documentation for Node.js itself, with no luck, then turning to Google, with most answers appearing to use Express.js. The answers seemed to point at req.connection.remoteAddress (which works, but breaks if used with a proxy) or req.headers['x-forwarded-for'], however this returned undefined when I tried to use it. Any help is greatly appreciated.

like image 484
LostEth0 Avatar asked Dec 28 '25 22:12

LostEth0


1 Answers

You almost had it, try:

var clientip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

This will set clientip to the correct value if a proxy is used. If no proxy is used, clientip gets set to the ip address of the client initiating the connection.

like image 191
mottek Avatar answered Dec 31 '25 11:12

mottek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!