How to use results from i18nextBrowserLanguageDetector

I'm trying to use i18nextBrowserLanguageDetector to detect the user's browser language settings and redirect them to the translated page if we support their preferred language. The first part of the code below seems to be working fine, and will cache the user's language preference in a cookie correctly.

import i18next from 'i18next';
import LngDetector from 'i18next-browser-languagedetector';

    detection: {
      // order and from where user language should be detected
      order: ['cookie', 'navigator', 'htmlTag', 'path'],

      // keys or params to lookup language from
      lookupCookie: LANG_COOKIE,
      lookupFromPathIndex: 0,

      // cache user language on
      caches: ['cookie']

However, the problem I have is that I want to do something based on the user's language setting but it seems like i18next runs their detection code asynchronously but doesn't provide any callback that I can see. Part of the problem is that their docs are really slim. What I've done is to add some code on document ready like so:

document.addEventListener('DOMContentLoaded', () => {
  const langPref = Cookies(LANG_COOKIE);
  if (!!langPref && SUPPORTED_LANGS.includes(langPref) && langPref !== currentLocale())
    window.location.href = `${location.origin}/${langPref}${location.pathname}`;

But the language cookie is never set by the time the page completes loading. I could add a setTimeout/Interval but that's kind of hacky and inefficient.

1 answer