How can i get user info with node.js

11,972

Solution 1

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 
}

Solution 2

You can use req.headers['accept-language'] for the language but for country you have to refer to the user IP, it's not a data you can get from useragent or headers.

Share:
11,972
Kerem Çakır
Author by

Kerem Çakır

Updated on June 14, 2022

Comments

  • Kerem Çakır
    Kerem Çakır almost 2 years

    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.