[Dev] Detecting user's language on Express.js

Last week we found that we're getting a lot of visitors from Russia and even they're sharing our articles to VK1, the largest Russian social network in Europe. After some research he found that some countries (Russia, Ukraine, Belarus, Kazakhstan and Uzbekistan) are using this social network more than even Facebook.

In order to be able to give our users from those countries a better way to keep in track with Hubii we've decided, as an experiment, to create a VK Page and show a widget from that social network in the articles.

We though to get the country of the user using the IP but it would mean one more query to retrieve that info that we don't want to affect ALL users only to do a experiment for a determined number of countries. So, we decided to go ahead using the header of the language. While that's not a perfect solution it's good enough for what we want to achieve here.

Now, as we're using Express.js we searched for a way to get the header 'accept-language'. I've found a solution in Stack Overflow about how to get the user's language, that was quite good, but digging on the documentation of Express.js finally found the best solution for us.

Since Express.js 4 you can use the request object req and his method acceptsLanguages to check if the request accept one or more languages. You'll need to know all the language codes2 in order to be able to check them but it's pretty simple.

var hasToShowVK = req.acceptsLanguages( 'ru', 'uk', 'ru-mo', 'be' );  

Pretty, simple and neat.