← Back to knowledge base |
  • Web development

Get visitor's country code in Node.js on Azure

In this article I will provide you with a code snippet that gives you visitor's country code from a website running in the Node.js environment on Microsoft Azure.

This might look like a trivial task but it took me a while to achieve that. I would like to dedicate this to my future self.

To get the coutry code we need:

  • Vistor's IP address,
  • Translate the address to a country code.

Get IP

There are npm packages (e.g.  ip) that do it for you and they perfectly work on localhost or environments like Heroku. Regrettably, Azure is a little black box that sometimes does things on it's own. What worked for me on Azure is:

var ip = req.headers['x-forwarded-for'].split(',')[1];

Azure behaves like a proxy and req.headers['x-forwarded-for'] hides the IP address that you need. From my experience Azure returns 2 comma-separated IP addresses and the second one is the one you are looking for.

Translate IP to a country code

Again, seems to be an easy task. But Azure makes it tricky. There are several npm packages that use the geoip database but only one works for me on Azure. The one is called geoip-native. I suppose the reason is that this package stores the geoip database in a csv file. The others use dat files and Azure ignores them. This is just an assumption. 

The full code snippet:

var geoip = require('geoip-native');

var getCountryByIP = (req) => {
  var ip = '96.84.57.209';  // A random US IP address as a default
  
  // Get the second IP address obtained from the 'x-forwarded-for' header
  if (typeof req.headers['x-forwarded-for'] !== 'undefined') {
    ip = req.headers['x-forwarded-for'].split(',')[1];
  }

  // Return the IP translated to a country code
  return geoip.lookup(ip).code;
}

// Sample usage
app.get('/', (req, res, next) => {
  if (getCountryByIP(req) === 'US') {
    res.redirect(301, '/us/overview');
  }
});

About the author

Milan Lund is a Freelance Web Developer with Kentico Expertise. He specializes in building and maintaining websites in Xperience by Kentico. Milan writes articles based on his project experiences to assist both his future self and other developers.

Find out more
Milan Lund