sveltekit-i18n / lib

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

error pages not translated when accessed in browser for the first time #149

Open jitterbux opened 10 months ago

jitterbux commented 10 months ago

Browser: Chrome 115.0.5790.170 os: macOS 13.2.1

If you try to visit https://locale-router-advanced.netlify.app/about/asdfasdfasdfasfdasdf

you will get:

error.shit.happens (404)
error.default

only after you reload the page manually again, you will then get the correct text:

Oh, dear... (404)
Page not found.

The same is true for the /cs/ and /de/ version.

UPDATE: It seems that not only for the first time but also if you leave the page open in the browser for a certain amount of time a few minutes and you refresh it, you get the error.shit.happens instead of Oh, dear... translation again. At least, for me it behaves like that. I noticed it when I tried to refreshed older tab I opened some time ago in Chrome.

MarilorV commented 6 months ago

Same for me. Did you or anyone found a solution ?

twoends commented 2 months ago

I got the same error. I fixed it adding the translations in the error object inside the hooks.server.ts

export const handleError: HandleServerError = async ({ event }) => {
    const errorId = crypto.randomUUID();
    const { locals } = event;
    const { lang } = locals;

    await loadTranslations(lang, 'error');

    return {
        message: 'Whoops!',
        errorId,
        translations: translations.get()  // <--- here
    };
};

and then using it to load the translation inside the error page

<script>
    import '../app.pcss';
    import { page } from '$app/stores';
    import { t, locale, addTranslations } from '$lib/i18n/translations';

    const { status } = $page;
    addTranslations($page.error?.translations);  // <--- here
</script>

<main>
    <h1>{$t('error.shit.happens')} ({status})</h1>
    <p>{$t(`error.${status}`, { default: $t('error.default') })}</p>
    <br />
    <br />
    {$locale} – {$t(`lang.${$locale}`)}
</main>

Remember to add the translations field into the app.d.ts to avoid typescript errors