xiCO2k / laravel-vue-i18n

Allows to connect your `Laravel` Framework translation files with `Vue`.
MIT License
620 stars 51 forks source link

Hydration text content mismatch with Inertia SSR #180

Closed kaspernowak closed 5 months ago

kaspernowak commented 5 months ago

I am struggling with using inertia SSR with localization, where I get a Hydration text content mismatch on warning.

As an example I set up a quick test project, with Home.vue looking like this:

<script setup>
import { trans } from 'laravel-vue-i18n';
</script>
<template>
    <div>
        <h1>{{ trans('test.hello') }}</h1>
    </div>
</template>

Then for brevity, I added this to my default inertia app.js :

import { i18nVue } from 'laravel-vue-i18n'

createInertiaApp({
  ...
  },
  setup({ el, App, props, plugin }) {
    ...
    .use(i18nVue, {
      resolve: async lang => {
        const langs = import.meta.glob('../../lang/*.json');
        return await langs[`../../lang/${lang}.json`]();
      }
    })
    .mount(el)
  },
})

And this to my ssr.js:

import { i18nVue } from 'laravel-vue-i18n'

createServer(page =>
  createInertiaApp({
    ...
    },
    setup({ App, props, plugin }) {
      const lang = process.env.VITE_APP_LOCALE || 'en';
      return createSSRApp({
        render: () => h(App, props),
      }).use(plugin)
      .use(i18nVue, {
        lang: lang,
        resolve: lang => {
          const langs = import.meta.glob('../../lang/*.json', { eager: true });
          return langs[`../../lang/${lang}.json`].default;
        },
      })
    },
  }),
)

When I load my Home.vue page, I get this warning and error in the browser console:

[Vue warn]: Hydration text content mismatch on <h1>​Hello in english​</h1>​ 
  - rendered on server: Hello in english
  - expected on client: test.hello 
 ...

Hydration completed but contains mismatches.
setup    @    app.js:25
Promise.then (async)        
(anonymous)    @    app.js:10
Show 5 more frames

So it seems like the client isn't hydrating the frontend with the translation on page load, which causes this mismatch. Is this something I should just ignore, or is there a way that I can fix this?

andreiio commented 5 months ago

I ran into this issue recently, paired with the translation keys flashing up on the screen during development, when the SSR was turned off.

Turns out the fix is fairly easy. You just mount the Vue app after the translation files got loaded, like in https://github.com/xiCO2k/laravel-vue-i18n/issues/117#issuecomment-1627295319.

xiCO2k commented 5 months ago

Thanks @andreiio