nuxt-modules / i18n

I18n module for Nuxt
https://i18n.nuxtjs.org
MIT License
1.72k stars 477 forks source link

baseUrl defined as function not working #3178

Open AndersCV opened 1 week ago

AndersCV commented 1 week ago

Environment


- Operating System: Linux
- Node Version:     v18.20.3
- Nuxt Version:     3.13.2
- CLI Version:      3.14.0
- Nitro Version:    2.9.7
- Package Manager:  npm@10.2.3
- Builder:          -
- User Config:      -
- Runtime Modules:  -
- Build Modules:    -
------------------------------

Reproduction

https://stackblitz.com/edit/nuxt-starter-qqn2vx

Describe the bug

in nuxt.config.ts define baseUrl as a function returning a string is not working correctly.

Problematic for apps with differentDomains: trueas the canonical url generated by the module for SEO purposes always points the defaultLocales domain regardless for the current active locale.

Additional context

No response

Logs

No response

drzastwakamil commented 1 week ago

I'am experiencing same issue. My i18n config:

i18n: {
    lazy: true,
    // works perfectly fine
    baseUrl: 'https://somedomain.com',
    // never gets executed
    // baseUrl: () => {
    //   return 'https://somedomain.com';
    // },
    langDir: 'locales',
    strategy: 'prefix_except_default',
    defaultLocale: 'de',
    locales: [
      {
        code: 'de',
        language: 'de',
        name: 'DE',
        files: ['german/de.locale.common.json', 'german/de.locale.units.json', 'german/de.locale.searchQuestions.json'],
      },
      {
        code: 'en',
        language: 'en',
        name: 'EN',
        files: [
          'english/en.locale.common.json',
          'english/en.locale.units.json',
          'english/en.locale.searchQuestions.json',
        ],
      },
    ],
  }

For some reason the function never gets executed.

drzastwakamil commented 1 week ago

I found a solution which I'am satisfied with. Might also help you. It's not ideal but it's working. I modify the baseURL using a Nuxt Plugin.

// plugins/i18dynamicBaseUrl.ts
export default defineNuxtPlugin((nuxtApp) => {
  // @ts-ignore
  nuxtApp.$i18n.baseUrl = useRequestURL().origin;
});

I use the useRequest() function since I want the baseURL to be dynamic based on the domain. But you can put any operations you want there.

I am not sure if that's a safe approach also however the result of useLocaleHead included the baseUrl in the paths so it looks like the Seo Requirements are met with this approach.

AndersCV commented 1 week ago

Ah yes that looks like a pretty good workaround meanwhile! Thanks for sharing.