1

So am trying to get the ip address of the visitors to my app on Haruko, am using an API for this, the API works well locally but when i deploy the app on Heroku, i get the IP of the Heroku server, it is an express.js app and am using this setting

app.set('trust proxy', true);

I have seen alot of solution to this problem but know works for me.

when i use

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

i get this result

clientIp: '::1',
Allaye
  • 623
  • 4
  • 15
user15317824
  • 67
  • 1
  • 6

2 Answers2

2

First you will have to install this module npm i ipware

var get_ip = require('ipware')().get_ip;


app.use(function(req, res, next) {
    var ip_info = get_ip(req);
    console.log(ip_info);
    // { clientIp: '127.0.0.1', clientIpRoutable: false }
    next();
});

Mind you the result is in an object form, getting the ipaddress should be simple as doing

ip_info.clientIp

So i guess this should help.

Allaye
  • 623
  • 4
  • 15
1
var ip = req.headers['x-forwarded-for'] || 
     req.connection.remoteAddress || 
     req.socket.remoteAddress ||
     (req.connection.socket ? req.connection.socket.remoteAddress : null);

But sometimes you can get more than one IP address with this req.headers['x-forwarded-for']

      var ipAddr = req.headers["x-forwarded-for"];
      if (ipAddr){
        var list = ipAddr.split(",");
        ipAddr = list[list.length-1];
      } else {
        ipAddr = req.connection.remoteAddress;
      }

You control with basic if else.

Or you can use this one and replace with req.headers['x-forwarded-for'] on top of the answer

let ip = request.headers['x-forwarded-for'].split(',')[0]
yahya007
  • 121
  • 7