The solution is heavily inspired by sveltekit-i18n/lib#94 (comment).
All kudos to @jonsaw. This is merely an adaptation to
svelte-i18n
.
- Support for SSR
- Example with user preference set by
Accept-Language
on the server andnavigator.language
on the frontend.
The first thing we need to do is to setup regular svelte-i18n
.
// src/lib/i18n/index.ts
import { browser } from '$app/environment'
import { init, register } from 'svelte-i18n'
const defaultLocale = 'en'
register('en', () => import('./locales/en.json'))
register('de', () => import('./locales/de.json'))
init({
fallbackLocale: defaultLocale,
initialLocale: browser ? window.navigator.language : defaultLocale,
})
For SSR we need to tell the the server what language is being used. This could use cookies or the accept-language header for example. The easiest way to set the locale in the server hook
// hooks.server.ts
import type { Handle } from '@sveltejs/kit'
import { locale } from 'svelte-i18n'
export const handle: Handle = async ({ event, resolve }) => {
const lang = event.request.headers.get('accept-language')?.split(',')[0]
if (lang) {
locale.set(lang)
}
return resolve(event)
}
On the frontend we need to set the language too, for this we could again use cookies, or in this example: window.navigator.language
.
// +layout.ts
import { browser } from '$app/environment'
import '$lib/i18n' // Import to initialize. Important :)
import { locale, waitLocale } from 'svelte-i18n'
import type { LayoutLoad } from './$types'
export const load: LayoutLoad = async () => {
if (browser) {
locale.set(window.navigator.language)
}
await waitLocale()
}
<!-- +layout.svelte -->
<slot />
<script lang="ts">
import { _ } from 'svelte-i18n'
</script>
<h1>Welcome to SvelteKit</h1>
<p>Visit <a href="https://kit.svelte.dev">kit.svelte.dev</a> to read the documentation</p>
{$_('my.translation.key')}