Milan Lund logo

Hi, I am Milan Lund!Full Stack Web Developer

I specialise in building websites and web applications with Kontent.ai and Kentico platforms.

  • Front-end

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:

Loading...

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:

Loading...