yuer
yuer

Reputation: 1

How can I get visitors IP by Node.js?

I have my own VPS server and I have script in Node.js which display the visitor's IP but always when I visit website I get in console local IP address (127.0.0.1). I use Nginx.

Any idea?

Node.js script:

#!/usr/bin/env nodejs

  const http = require('http');

  const host = '127.0.0.1';

  const port = 8080;

  const server = http.createServer((req, res) => {

  res.statusCode = 200;

  res.setHeader('Content-Type', 'text/plain');

  var ip = (req.headers['x-forwarded-for'] || '').split(',').pop().trim() || 
  req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;


console.log(`IP = ${ip}`);

});

server.listen(port, host);

Nginx proxy/headers configuration:

server {

  listen 80 default_server;

  listen [::]:80 default_server;

  root /var/www/html;

    
  index index.html index.htm index.nginx-debian.html;

  server_name _;

  location / {
            
           try_files $uri $uri/ =404;
           proxy_pass http://127.0.0.1:8080;
           proxy_http_version 1.1;
           proxy_set_header Upgrade $http_upgrade;
           proxy_set_header Connection 'upgrade';
           proxy_set_header Host $host;
           proxy_cache_bypass $http_upgrade;
 }
 }

   

Upvotes: 0

Views: 258

Answers (1)

O. Jones
O. Jones

Reputation: 108836

You need to rig your nginx reverse proxy to pass along the requester's IP address. Adding these two settings to nginx.conf does the trick.

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

Put these lines in your location{...} stanza of nginx.conf along with your proxy-pass and the rest.

With these changes, nginx inserts two http headers into each request: X-Forwarded-For and X-Real-IP. (There's a new standard Forwarded: header, but nginx doesn't handle it easily as of mid-2020.)

Then, use app.set() to add proxy server support to your nodejs program to interpret those headers. Put this line in your www or http-server.js Javascript program shortly after your const app = express() line.

app.set( 'trust proxy', 'loopback' )

Express will then muck around with the X-Forwarded-For header for you and put the appropriate IP address in req.ip.

I've linked to some documentation. You would be wise to read it.

Upvotes: 1

Related Questions