Svelte Simple Lang (SSR MODE)

i18n for Svelte - Docs Github

Go to Home


SSR Mode

Your lang: id it randomly generate for simulate ssr mode
Available locale: id, en


// src/routes/layout.server.ts
import type { LayoutServerLoad } from './$types.js';

export const load: LayoutServerLoad = async ({ url }) => {
	const params = url.searchParams;
	const paramsLang = params.get('lang') || '';

	// Generate randomly (in a real app, you might use a database to store the locale for each user)
	const lang = (
		['id', 'en'].includes(paramsLang) ? paramsLang : Math.random() > 0.5 ? 'id' : 'en'
	) as 'id' | 'en';

	return {
		lang
	};
};

	

// +page.svelte
import { availableLocales, getLocale, setLocale, setDefaultLocale, t } from '$lib/lang/i18n.js';
import type { PageProps } from './$types.js';

const { data }: PageProps = $props();

setDefaultLocale(lang);

const toggleLocale = async () => {
	const locale = getLocale();
	const newLocale = locale === 'en' ? 'id' : 'en';
	await setLocale(newLocale);
	// hit api for change user language in database
};
	
    
en.json
{
	"world": "World",
	"hello_{name}": "Hello {name}",
	"you_have_{count}_apple": "You have {count} apple",
	"you_have_{count}_apple_plural": "You have {count} apples",
	"you_have_{count}_item": "You have {count} item"
}


id.json
{
	"world": "Dunia",
	"hello_{name}": "Halo {name}",
	"you_have_{count}_apple": "Kamu punya {count} apel",
	"you_have_{count}_apple_plural": "Kamu punya {count} apel",
	"you_have_{count}_item": "Kamu punya {count} item"
}
    
  

Current lang: id



{t('world')}

Dunia