Search code examples
nuxt.jsi18nextvue-i18nnuxt-i18nnuxt3.js

Switch i18n locale in a Nuxt 3 plguin Nuxt-i18n


I'd like to switch the locale in my Nuxt 3 project in a plugin based on some logic in router.beforeEach(), however, when I try to access the i18n nuxt module in the plugin:

export default defineNuxtPlugin((nuxtApp) => {
    const i18n = useI18n()
})

I get a server 500 error Must be called at the top of a 'setup' function.

What I tried: I was able to switch the locale by using nuxtApp.$i18n.setLocale(pageLang) in the plugin, but that doesn't update the SEO attributes in the head (the useLocaleHead() ref). I assume that this is the case because it changes the locale of the Vue i18n instance but the nuxt module doesn't register the change. Please correct me if I'm wrong.

How could I switch the locale in the plugin before navigating to a route & also update the nuxt i18n module refs? I would also like the locale change to happen on the server so that the server-rendered content is not always in the default locale.


Solution

  • I solved it using

    nuxtApp.$i18n.locale.value
    

    to get the current locale