sveltekit-i18n / lib

Internationalization library built for SvelteKit.
MIT License
447 stars 28 forks source link

Translations are not rendered during SSR #160

Closed PaulMaly closed 7 months ago

PaulMaly commented 7 months ago

I don't see any translations/locales in SSR output. Texts appearing only on frontend. Could you please give me any ideas why it can happened?

jarda-svoboda commented 7 months ago

As far as I know, everything works well in terms of SSR within our examples have you tried to use some of them in your project? I think there might be an issue with your implementation..

PaulMaly commented 7 months ago

Actually, I just copy relevant parts of multi-page example, eg. cookie usage, reading the header etc, but replaced the loading of local translations files by my backend. I just start to test it with sveltekit and looks like I don't have much self-written code to face with implementation issue. I've +layout.server with such content:

import { locales, loadTranslations } from '$lib/services/i18n';
import { getLocale } from '$lib/services/api';

export async function load({ url, cookies, request, fetch }) {
    const { pathname } = url;

    // Try to get the locale from cookie or user preferred locale
    const localeCode =
        cookies.get('locale') || `${`${request.headers.get('accept-language')}`.match(/[^(,|;)]*/)}`;

    const supportedLocales = locales.get();

    const locale = await getLocale(
        fetch,
        supportedLocales.includes(localeCode) ? '/' + localeCode : ''
    );

    await loadTranslations(locale.locale, pathname);

    return {
        locale
    };
}

And +layout.js with this:

import { setLocale, setRoute } from '$lib/services/i18n';

export async function load({ url, data }) {
    const { pathname } = url;
    const { locale } = data;

    await setRoute(pathname);
    await setLocale(locale.locale);

    return {
        locale
    };
}

In SSR output I see all necessary markup (html elements, forms, button etc) except texts. All places where I expect text are replaced by fallback values from sveltekit-i18n config, like:

const config = {
    fallbackValue: '-',
    loaders: [...]
};
<h1 data-aos="fade-up-sm" class="mb-6 text-[35px] sm:text-[50px] xl:text-[65px]">
  -
</h1>

What am I did wrong? Will be appreciated for any ideas )))

PaulMaly commented 7 months ago

The issue solved. Looks like, I had the problems with universal fetch requests on server-side. Fetch was working only on client, thats why text appears only on frontend side