Insights

Using Cloudflare Workers For URL Language Embedding In Sitecore

Introduction

If you have a multi-language site, it's always a good idea to put the language in the URL, as it helps SEO.

If you're looking for a way to remove the language embedding, check out this blog.

Instead of creating a custom language resolver, and having to go to the trouble of changing config files, deploying code, waiting for Sitecore to restart, etc, we can use Cloudflare's Workers to add the language to the URL.

Step-By-Step Guide

Select Workers in the sidebar, then Create a Service.

Select Works from the Cloudflare sidebar.

Select Create a Service from the Cloudflare workers menu

You should see the following screen. You can use whatever name you like. Click Create service to continue.

Cloudflare Create a Service HTTP Handler step

Select Quick edit on the top-right.

Select Quick Edit on the Cloudflare Worker setup step 2 screen

Example Code

The following code is code for an example website, that has two languages, English and French. If there is no language in the embed, it will default to English.


const statusCode = 301;
const english = 'en';
const french = 'fr';

addEventListener("fetch", event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {

  // if method is not a GET, return
  if(request.method !== 'GET')
  {
    return fetch(request);
  }

  //get request url
  var requestURL  = new URL(request.url);
  var { protocol, host, pathname, search, hash } = requestURL;

  //get browser language
  var languageHeader = request.headers.get('accept-language');
  
  //default to english if browser has no language
  if(!languageHeader)
  {
    var destinationURL = 'https://' + host + '/en' + pathname + search + hash;
    destinationURL = destinationURL.endsWith('/') ? destinationURL.slice(0, -1) : destinationURL;
    return Response.redirect(destinationURL, statusCode)
  }

  //check if address already has english and french specified
  const pathSplit = pathname.split('/');

  if (pathSplit[1] == english || pathSplit[1] == french)
  {
    return fetch(request);
  }

  //add en or fr depending on browser language
  if (languageHeader.includes(english)) {
    var destinationURL = 'https://' + host + '/en' + pathname + search + hash;
  }
  else if (languageHeader.includes(french)) {
    var destinationURL = 'https://' + host + '/fr' + pathname + search + hash;
  }

  //remove trailing slash
  destinationURL = destinationURL.endsWith('/') ? destinationURL.slice(0, -1) : destinationURL;

  //redirect
  return Response.redirect(destinationURL, statusCode)

}
    

When you are finished editing the code, click Save and Deploy at the bottom.

Adding Routes

Now that we have our worker up in production, we need to create Routes that trigger it.

Navigate back to the Workers page by clicking the Cloudflare logo in the top left, selecting your account, selecting your website, then selecting Workers on the sidebar.

You should be on the following page. Click Add route to continue.

Select Add Route on the Cloudflare Worker Setup Screen

The following rule is a rule that will cover every page on our website. The route field contains the URL we want to match, and the Service field is the worker we want to use.

Add a Route step in setting up a new worker in Cloudflare

Adding Exclusion Routes

We don't want every page on our website to have a language embed.

Examples of pages we would want to exclude would include Sitecore, images, styling pages, scripts, formbuilder, etc.

To create an exclusion, click Add route again. This time, leave the Service on None.

Adding exclusion routes in setting up a Cloudflare worker

Conclusion

Using Cloudflare's Workers, we have set up a custom language embed without the hassle of compiling code or deploying config changes to Sitecore. The flexibility of Javascript lets us deploy and test quicker.

👋 Hey Sitecore Enthusiasts!

Sign up to our bi-weekly newsletter for a bite-sized curation of valuable insight from the Sitecore community.

What’s in it for you?

  • Stay up-to-date with the latest Sitecore news
  • New to Sitecore? Learn tips and tricks to help you navigate this powerful tool
  • Sitecore pro? Expand your skill set and discover troubleshooting tips
  • Browse open careers and opportunities
  • Get a chance to be featured in upcoming editions
  • Learn our secret handshake
  • And more!
Sitecore Snack a newsletter by Fishtank Consulting
 

Meet Gorman Law

Full Stack Developer

🏋️🎸🏈

Gorman is a Full Stack Developer and a University of Calgary alumni who has a background in Canada's financial industry. Outside of work, he likes to go rock climbing, try out new ice cream places, and watch sports.

Connect with Gorman