node.jsexpressbrowsersocket.iouserinfo

How can i get user info with node.js


I am using express.js

I should learn user's browser name, browser language, country. How can i learn these ?

I tried useragent but i think it just give browser.


Solution

  • You can get a bunch of information from the request headers. The user country will be more difficult, you will likely need to look it up from the IP address of the request. NB: This is not perfectly reliable and of course depends on getting the original request, not any proxy server address. You can use a library like geoip-lite for this (https://www.npmjs.com/package/geoip-lite).

    I'd do something like:

    var app = express();
    app.set('trust proxy', true);
    
    var geoip = require('geoip-lite');
    
    app.get('/test', function(req, res){
    
        console.log('Headers: ' + JSON.stringify(req.headers));
        console.log('IP: ' + JSON.stringify(req.ip));
    
        var geo = geoip.lookup(req.ip);
    
        console.log("Browser: " + req.headers["user-agent"]);
        console.log("Language: " + req.headers["accept-language"]);
        console.log("Country: " + (geo ? geo.country: "Unknown"));
        console.log("Region: " + (geo ? geo.region: "Unknown"));
    
        console.log(geo);
    
        res.status(200);
        res.header("Content-Type",'application/json');
        res.end(JSON.stringify({status: "OK"}));
    });
    

    The request headers will contain a bunch of useful stuff, an example:

    Headers: 
    {
        "host": "testhost:3001",
        "user-agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "accept-language": "en-US,en;q=0.5",
        "accept-encoding": "gzip, deflate",
        "connection": "keep-alive",
        "upgrade-insecure-requests": "1"
    }
    

    An example of the geo object would be:

    { 
      country: 'US',
      region: 'FL',
      city: 'Tallahassee',
      ll: [ 30.5252, -84.3321 ],
      metro: 530,
      zip: 32303 
    }