DEV Community

loading...
Cover image for Redirect your users to the right language using session storage (i18n)

Redirect your users to the right language using session storage (i18n)

codetraveling profile image Lars Originally published at blog.larsbehrenberg.com ใƒป3 min read

*This post was first published on my blog.

As a freelancer living and working in Japan, I had been asked many times in the past if I could translate my website to Japanese. And so finally, at the beginning of December, I created a Japanese and German version of my so far English website. It was a lot of fun testing different ways of doing this and if you are curious and are thinking of doing something similar yourself, I can highly recommend using Gatsby with Prismic as CMS!

However, after running my new website for a while, I started getting feedback from my users that it would be nice to be redirected to your "correct" language on page load. Instead of having to choose the language yourself after everything is already loaded.

In this tutorial, we will learn how to redirect your users to their "correct" language and then use session storage as a memory, so that the user can still access other languages without being forcibly redirected every time.

Let's get started!

Table Of Contents

Set up your path structure

Of course, there are many different ways to solve this issue of redirecting your users and in some, you might not even want to use something like session storage as memory. However, in my case I wanted the user to know that there are different languages and then even let the user choose which language to access after he had been redirected once to the browser set default language.

So, the path structure that I chose for my website for that reason looks like this:

  • "/en/page-one"
  • "/jp/page-one"
  • "/de/page-one"

With this type of structure, you can have Gatsby's navigate function simply swap out the language code in the URL. With this out of the way, let's go and write some code.

Redirect your user on page load

*Note, that in this example we use Gatsby's navigate function, but this can quite simply be replaced with their respective counterparts in React or NextJS.

There are 3 parts to this example.

  1. React.useEffect to prevent the language redirect function from looping and only run once on page load
  2. Getting the right URL from the getRedirectLanguage function based on the "navigator" (a browser API to detect the browser's language)
  3. Passing the correct language key into Gatsby's navigate function to replace the current URL.
import React, { useEffect } from "react";
import { navigate } from "gatsby";

const getRedirectLanguage = () => {
  if (typeof navigator === `undefined`) {
    return "en";
  }

  const lang = navigator && navigator.language && navigator.language.split("-")[0];
  if (!lang) return "en";

  switch (lang) {
    case "ja":
      return "ja";
    case "de":
      return "de";
    default:
      return "en";
  }
};

const IndexPage = () => {
  useEffect(() => {
    const urlLang = getRedirectLanguage();

    navigate(`/${urlLang}`);
  }, []);

  return (
        // ... your components here
    );
};

export default IndexPage;
Enter fullscreen mode Exit fullscreen mode

With this, you are already set to redirect your user to the correct language. But what if that user doesn't want to be redirected every single time, but instead wants to use a language switch like this one afterward?

Choose your language

Use session storage as memory

This is where session storage comes in handy. Look at this example where a simple if clause is added in the React.useEffect statement:

useEffect(() => {
  if (!sessionStorage.getItem('loggedin')) {
    sessionStorage.setItem('loggedin', true)

    // => then redirect
    const urlLang = getRedirectLanguage()
    navigate(`/${urlLang}`, { replace: true })
  }
}, [])
Enter fullscreen mode Exit fullscreen mode

With this, if sessionStorage has not been set, the user won't be redirected and can freely browse the website. But if the user comes onto your website for the first time or for the first time in a while, he will be redirected to his or her default browser language. Pretty cool, right?

Of course, this doesn't hold up to some more sophisticated ways of doing this, but for 2 lines of code without using cookies, this saved me a lot of trouble.

And thatโ€™s pretty much it!

Thanks so much for reading this far and feel free to reach out to me anytime, on my website or Twitter ๐Ÿ™‚ And if you like to read more, make sure to check out my other posts on my blog

Discussion (0)

pic
Editor guide