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:
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.
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 ✨
Please check this link for an updated answer
https://stackoverflow.com/questions/59908989/redirect-based-on-browser-language-in-gatsby/60293794
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.