tableflip / how-to

:question: How to TABLEFLIP and other stories
4 stars 0 forks source link

How to guess the users country by IP #4

Open olizilla opened 9 years ago

olizilla commented 9 years ago

Use https://www.npmjs.com/package/geoip-ultralight

var geoip = require('geoip-ultralight');
// Unlike geoip-lite's lookup() call, geoip-ultralight exposes 
// a lookupCountry() function to avoid confusion 
var ip = "207.97.227.239";
geoip.lookupCountry(ip); // => "US" 

You'll probably be running behind some kind of frontend proxy, so the host header on incoming requests will be useless, as it'll be the IP of the proxy rather than the client.

The X-Forwarded-For header is your friend. Have nginx add them for you with:

  location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://localhost:3000;
  }

And then you can pull the client ip from there or have express/keystone do it for you by setting:

"trust proxy": true

See: