internationalizationnuxt.jsvue-i18nnuxt-i18n

@nuxtjs/i18n redirect to the available translations


I have 3 languages on my website but not all the pages support all that three languages.

Problem: a user visits my website and from the URL he changes the prefix to a language that the page does not have a translation to, the page will load with the key's names so the page content will look something like this: mypage_header etc...

What I tried :

1- according to nuxt/i18n docs there is an option to set the available languages on every page but the thing is: if the language is not available the user will be redirected to the 404 page, I want to change that, so he gets redirected to the available translation of that page.

2- There is an option called Locale fallback

Summary: Use fallbackLocale: '' to choose which language to use when your preferred language lacks a translation

This worked with the problem that it changes to an existed language but the direction remains the same, so if I have an English translation for a page and the user changed the route to the Arabic version, the direction will not change from ltr to rtl .

Example:

If the page has English language and the user changes the URL from /en to /fr I want the user to get redirected to the English version of that page since it is the only available language for this page. How can I achieve such a thing?

nuxt.config.js

i18n: {
  locales: [
    { code: "en", iso: "en", file: "en.js", dir: "ltr" },
    { code: "ar", iso: "ar", file: "ar.js", dir: "rtl" },
    { code: "fr", iso: "fr", file: "fr.js", dir: "ltr" },
  ],
  lazy: true,
  baseUrl: "https://example.com",
  defaultLocale: "ar",
  strategy: "prefix_and_default",
  langDir: "~/lang/",
  detectBrowserLanguage: {
    useCookie: true,
    cookieKey: 'i18n_redirected',
    redirectOn: 'root',  // recommended
  },
}

Solution

  • The Locale fallback was the right solution, it was my mistake, in the translation files which are en.js, fr.js, and ar.js : I was putting my translations in mixed formats: JSON and JS object formats rather than putting it in either JSON only or JS object only, changing all the translations format to JS object only, fixed the problem for me.