NuxtN
Nuxt13mo ago
-

Dynamically load i18n messages based on context

I'm using @nuxtjs/i18n and was wondering if it's possible to dynamically load/switch messages based on context (in my case, context is organization). In my case, organizations are of different types/templates, and for some organization templates, I would like to switch the messages to use different terminology.

I tried to achieve this using lazy loading:

// nuxt.config.ts
export default defineNuxtConfig({
  i18n: {
    // Module Options
    strategy: 'no_prefix',
    locales: [
      {
        code: 'en',
        file: 'i18n/locales/en.ts'
      }
    ],
    lazy: true,
    defaultLocale: 'eb',
    experimental: {
      localeDetector: './localeDetector.ts',
    },
  },
})


// i18n/locales/en.ts
export default defineI18nLocale(async (locale) => {
  const route = useRoute()
  const organization = route.params.organization as string
  return await $fetch(`/api/${organization}/i18n/${locale}`)
})


// app.vue
<script setup lang="ts">
const { locale, loadLocaleMessages } = useI18n()
const organization = useOrganization()

watch(organization, async () => {
  await loadLocaleMessages(locale)
}, {
  immediate: true,
})
</script>
<template>
  <div>
    <NuxtRouteAnnouncer />
    <!-- <VitePwaManifest /> -->
    <NuxtLayout>
      <NuxtPage />
    </NuxtLayout>
  </div>
</template>


However, because I'm using useRoute() in that handler, it results in the following error:

ssr:error Failed locale loading: [nuxt] A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function. This is probably not a Nuxt bug. Find out more at `https://nuxt.com/docs/guide/concepts/auto-imports#vue-and-nuxt-composables`. 


How can I best achieve dynamic loading of messages based on a context other than locale? (e.g. based on a certain route param)
Was this page helpful?