Gatsby: [SOLVED] How to redirect based on browser language?

Created on 18 Feb 2020  Â·  4Comments  Â·  Source: gatsbyjs/gatsby

One of the requirements of the website that I'm working on is to redirect the user based on the language preferences.
So, if the language of the browser is in English it will go to /en

This is the code that I've on pages/index.js

import React from 'react'
import { Redirect } from '@reach/router';

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';
    default:
      return 'en';
  }
}
const IndexPage = () => {
  return (
    <Redirect to={`/${getRedirectLanguage()}`} noThrow/>
  )
}
export default IndexPage

But the page is not being rendered. If I refresh the page, the page is being redirected to /en/ which now renders the page. How can I redirect based on browser language?

I noticed that there is a thread related to this but there is not a proper solution:

7707

Note: I don't want to use Window Location because that looks more like a quick fix rather than a solution. Also, I don't know the SEO implications for this.

question or discussion

Most helpful comment

I think because you return <Redirect /> as component.

Have you try to put the logic into useEffect?
So the code will be like this.

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";
    default:
      return "en";
  }
};

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

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

  return null;
};

export default IndexPage;

All 4 comments

I think because you return <Redirect /> as component.

Have you try to put the logic into useEffect?
So the code will be like this.

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";
    default:
      return "en";
  }
};

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

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

  return null;
};

export default IndexPage;

@idindrakusuma is working!!! thank you!

@idindrakusuma is working!!! thank you!

Sure! Then, I will close this issue.
Thanks for using Gatsby @alfred-pb ✨

Was this page helpful?
0 / 5 - 0 ratings