Next.js Discord

Discord Forum

i18n Change Locale Based on Location

Unanswered
Asian paper wasp posted this in #help-forum
Open in Discord
Asian paper waspOP
We've got 10 languages setup in the Next.js config file, and we have all of the translations setup correctly for this. If we navigate to a page with a language manually, everything works fine.

Example:
// this loads Japanese
/ja/contact

// this loads English
/contact

The only problem we have now, is that the language doesn't auto-detect and redirect. I've tested this with ExpressVPN and the languages don't change based on the location. I'm pretty sure that ExpressVPN isn't the issue as my wife uses it to access Netflix Japan.

All of my research says that adding this to the config will fix that.
import LanguageDetector from 'i18next-browser-languagedetector';

i18next.use(LanguageDetector).init();


What am I missing here?

3 Replies

Toyger
from i18next-browser-languageDetector source code
looks like they don't have detection of location by ip
order: ['querystring', 'cookie', 'localStorage', 'sessionStorage', 'navigator', 'htmlTag'],


you can try to change browser default language, and try after that in incognito, it should work with 'navigator' detection.
Asian paper waspOP
That works great on the home page, but not any other pages. Since that is the required entry point, I can use that with local storage or cookies to make the rest of them work. Will report back soon.
Asian paper waspOP
Solution.
export async function getServerSideProps(context) {
  const preferredLanguages = context.req.headers['accept-language'];

  return {
    props: {
      locale: preferredLanguages.split(',')[0]
    }
  };
}
class AwesomeClassName extends React.Component<PageProps> {
  constructor(props: PageProps) {
    super(props);
    i18next.changeLanguage(this.props.locale);
  }
}