Don’t set your website language based on user location

Catalin Ionescu
Modern Rails
Published in
May 24, 2020

I was in awe reading Stop setting the language of your website based on user location. The sheer simplicity of that idea and the impact is huge.

Want an example? I always use a VPN. Chrome is set to English for me. My VPN was set to Germany. I refreshed the Google Adsense page I was looking at and got automatically redirected to the .de page.

While Pedro Pimenta’s article suggests using javascript to set the locale, this is often unfeasible as the translations are done server-side. Let’s take a look at an approach to do this in Rails.

Thankfully, the language is set as an HTTP header. Take a look at mine:

accept-language: en-GB,en-US;q=0.9,en;q=0.8

Let’s break it down. Some languages have q-values — the relative quality factor (it specifies what language the user would prefer on a scale of 0 to 1).

In Ruby on Rails, you can access HTTP headers in a controller with request.env['HTTP_ACCEPT_LANGUAGE']. You can parse this string using the http-accept gem.

languages = HTTP::Accept::Languages.parse("en-GB,en-US;q=0.9,en;q=0.8")languages[0].locale # en-gb

Now, we can set this locale using the approaches suggested by the Rails Guides. In…

--

--

Catalin Ionescu
Modern Rails

Director of Applications Engineering. Bristol University alumnus.