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');
}
});Further reading
all postsBoost Conversions: Persist Form Data After Redirect in Xperience by Kentico
When users submit a form and are redirected to a thank-you page, a fundamental challenge emerges: the form submission data vanishes. This happens because HTTP redirects are statele…
Guide to Repository pattern with a Generic type in Xperience by Kentico
The Repository pattern in C# is a design pattern used to manage data retrieval from a data source. It acts as a mediator between the data access layer and the business logic layer …
Handling Search Index Rebuilds in Xperience by Kentico’s SaaS Environment
If your website is hosted on Kentico’s SaaS platform and you’re using Lucene for search functionality, you may have noticed search index issues after deployments. In this article, …