mbm
mbm

Reputation: 105

Get to know my client ip in nodejs app

I have two tier app structure(Nginx(proxy)+nodejs(app).End of the day I need to get my client IP(who visited my site) in my application(nodejs). Now my client IP, it's getting logging in my Nginx log file (by enabling the below conf

   proxy_set_header X-Real-IP $remote_addr;
   proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

Now I am getting the Nginx server IP in my app server, But I don't want to get my Nginx server IP, instead of that I need to get my original client IP in my app

This is the app code, which we are using to get the client IP in app server.

request.headers['x-forwarded-for'] || request.info.remoteAddress

Where; Nodejs-- > Happijs framework

Upvotes: 1

Views: 610

Answers (2)

Shubham Verma
Shubham Verma

Reputation: 9913

You should use below code :

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

If you are using Hapi framework then you should use below code:

var ip = request.headers['x-forwarded-for'] || request.info.remoteAddress;

Upvotes: 1

Amulya Kashyap
Amulya Kashyap

Reputation: 2373

SOLUTION_SOURCE : get ip user with nginx and node,

You can configure NGINX to pass the client's IP address with the following setting:

location / {
    proxy_pass https://fotogena.co:8000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;  # This line.
    proxy_connect_timeout   1000;
    proxy_send_timeout      1500;
    proxy_read_timeout      2000;

}

You can then use the HTTP header X-Real-IP from req.headers["X-Real-IP"].

Upvotes: 0

Related Questions