Velo Tutorial: Redirecting Visitors Based on Browser Language

You can use Velo to redirect visitors to different language versions of your site.

Most browsers have settings that let you define what language to view content in. Velo can access these settings and use them when displaying your site.

For example, if your browser locale is set to an English-speaking country, you can use Velo to redirect visitors to your site in English. If your browser locale is set to a Spanish-speaking country, you can redirect visitors to the Spanish version of your site.

This tutorial has 2 parts:

  • Instructions on how to get set up, including code you can copy and paste onto your page
  • An explanation of what each line of code does

Instructions

  1. Go to the page to redirect the visitor from.

  2. Open the code editor.

  3. Copy and paste the code below.

  4. In the copied code, make sure to substitute your locale codes and URLs, removing the < and \> symbols.

    Example

    For French, substitute <locale-code> with fr.

    To change the URL and its locale, substitute http://<your-URL>/?lang=<locale> with http://www.theCatalog.com/?lang=fr.

    Tip: To get the URL, just go to your live site, navigate to the relevant page in the right language and copy it the URL.

  5. Publish the page to see the redirect in action. The redirect will not work in preview mode.

Copy

A sample implementation of this code is provided below.

Understanding the Code

We are now going to understand the code using a scenario. The sample code below checks the browser locale, and then redirects the visitor to a catalog (www.theCatalog.com) in the right language. The code checks if the language of the browser is French, German, Chinese, or Spanish. If none of these match, the catalog displays in English.

Import statements on lines 2 and 3 bring in the APIs we need:

Copy

The redirect occurs after a time delay. This gives the visitor time to see notices on the page you are redirecting from. Line 4 contains the setTimeout function that creates this delay.

Copy

We add a switch statement on line 16 to check the browser locale. 

Copy

Notes

  • In line 48, the sample code defaults to English if the locale is not French, German, Chinese, or Spanish.  
  • We also make sure that the page does not reload if no language code is specified in the URL.
Was this helpful?
Yes
No