Change locale

The following function can be used to change the locale. Set a cookie to remember the user's choice and update the url according to how you store the locale in the url. If you don't store it in the url, just set the cookie and reload the page.

lib/poly-i18n/changeLocale.ts
ts
import { goto } from "$app/navigation";
import type { LocaleCode } from "./locales";
export function changeLocale(locale: LocaleCode, url: URL) {
setLocaleCookie(locale);
url.searchParams.set('lang', locale);
goto(url, { invalidateAll: true }) // SvelteKit method
// location.assign(url.href); // framework-agnostic method
}
function setLocaleCookie(locale: LocaleCode) {
const HUNDRED_YEARS = 60 * 60 * 24 * 365 * 100; // seconds * minutes * hours * days * years
document.cookie = `locale=${locale}; max-age=${HUNDRED_YEARS}; path=/; samesite=strict`;
}

That's all you need to do to set up your own implementation of poly-i18n. Now you can play with the result in this Kitbook, or learn about a few [Advanced Options].

Edit page in GitHub