Go to main content

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.

Get visitor's country code in Node.js on 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');
  }
});
Milan Lund

is a freelance web developer and a proud Basenji owner. His specialties are Kentico CMS/EMS and Kentico Cloud.

Further reading

all posts
  • Kentico CMS & EMS

    How do we teach university students to use Kentico

    From time to time a Kentico partner ask me if I could relocate myself permanently and work for them full time. Unfortunately, I can’t do that because I am a freelancer and I am loy…

  • Kentico CMS & EMS

    How to add a column to UniGrid in Kentico admin

    In this post I will show you the way how to add a column to a UniGrid table in Kentico admin on an example of Product coupons.

  • Kentico CMS & EMS

    How to install Kentico step by step

    The Kentico documentation comprehensively describes all the standard ways how to install Kentico on your machine but in a very general way. So there is no step by step tutoria…