Description
Hello! I've been using this library for a couple of months with SSR. I have followed the locale-router
example.
In that example, the layout.server.ts
is in charge of loading the needed translations and sending them to the other pages (namely, layout.ts
/layout.js
). After loading the translations, layout.server.ts
returns translations: translations.get()
. As noted in the locale-param
examples, the translations
variable on server contain all translations loaded by different clients.
This means that, after loading the needed translations based on route and locale, the server then sends ALL loaded translations to the client, not just the needed ones. This can easily be verified on the HTML output: all translations that the server has loaded so far are sent, including unneeded languages and unneeded keys from other routes.
I haven't found an option in the library to automatically strip unneeded translations, so I have developed my own utility function in layout.server.ts
:
// Remove unneeded translation keys and languages
const getStrippedTranslations = (lang: string, route: string) => {
const keysToLoad = [
...new Set(
config.loaders
.filter(
(loader) => !loader.routes?.length || loader.routes.some((r) => new RegExp(r).test(route))
)
.map((loader) => loader.key)
)
];
return {
[lang]: Object.fromEntries(
Object.entries(translations.get()[lang]).filter(([key]) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if (AVAILABLE_LANGUAGES.includes(key as any)) return true;
if (keysToLoad.some((keyToLoad) => key.startsWith(keyToLoad))) return true;
return false;
})
)
};
};
export const load: LayoutServerLoad = async ({ url, locals }) => {
const { pathname } = url;
const { lang } = locals;
await loadTranslations(lang, pathname);
return { i18n: { route: pathname, lang }, translations: getStrippedTranslations(lang, pathname) };
};
I believe this optimization should be handled automatically by the library, as the payload can become quite large for websites with a lot of content.