Search code examples
javascriptnode.jsexpressheroku

Return ip address of site visitors instead of Heroku server


So am trying to get the IP address of the visitors to my app on Heroku, 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 is using this setting

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

I have seen a lot of solutions to this problem but none of the solutions works for me.

when i use

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

i get this result

clientIp: '::1',

Solution

  • 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.