Search code examples
nuxt.jsnuxt-i18n

Nuxtjs i18n locale is always set to 'en' on the first load of a static generated page


I am using the Nuxt i18n module in my website for the localized content.

I have it setup as follows in nuxt.config.js:

[
  'nuxt-i18n',
  {
    locales: ['en', 'fr', 'ar'],
    defaultLocale: 'en',
    strategy: 'prefix',
    vueI18n: {
      fallbackLocale: 'en',
      messages: {
        en: {
          welcome: 'Welcome'
        },
        fr: {
          welcome: 'Bienvenue'
        },
        ar: {
          welcome: 'أهلا بك'
        }
      }
    }
  }
]

After doing the following:

npm run generate
npm run start

And clearing site data in my browser I attempt to access:

http://localhost:3000/ar/

The locale gets set to 'en' and I get redirected to

http://localhost:3000/en/

But now if I try again with the locale set to 'ar' the page loads with the correct locale (in this case: 'http://localhost:3000/ar/')

I also tried setting the defaultLocale and fallbackLocale to 'ar' instead of 'en' and testing everything again. But I got the same result.

Any suggestions or ideas on why this is happening and how to fix it are much appreciated. Thank you in advance


Solution

  • Nuxt i18N tries to detect the preferred language on first run, which probably means your browser language is set to English.

    This is the default way of working for this script, and it can be configured otherwise: https://i18n.nuxtjs.org/browser-language-detection.

    Once you change to another language, the setting can be stored in a cookie.

    If you have to be able to send localized links (/ar/ etc.) to your clients etc., you could maybe use a URL parameter: ?lang=es for example. You can create a little onMounted() script that checks if the param is present in the url when the page loads, and if so, it force redirects from the default url to the URL you want to share.