[](https://badge.fury.io/js/sveltekit-i18n) [](https://github.com/sveltekit-i18n/lib/actions/workflows/tests.yml) # sveltekit-i18n A lightweight, powerful internationalization (i18n) library designed specifically for [SvelteKit](https://github.com/sveltejs/kit). This package combines [@sveltekit-i18n/base](https://github.com/sveltekit-i18n/base) with [@sveltekit-i18n/parser-curly](https://github.com/sveltekit-i18n/parsers/tree/master/parser-curly) to provide the quickest way to add multilingual support to your SvelteKit applications. ## Why sveltekit-i18n? - ๐ **SvelteKit-optimized** โ `sveltekit-i18n/kit` wires hooks, layouts and components: an instance per request on the server, one per tab in the browser - ๐ฆ **One install** โ The core and the parser come with it; nothing else to add - โก **Smart loading** โ Translations load only for visited pages (lazy loading) - ๐ฏ **Route-based** โ Automatic translation loading based on your routes - ๐ง **Flexible** โ Support for custom data sources (local files, APIs, databases) - ๐งฉ **Extensible** โ Add surfaces (Svelte stores, keys as members of `t`, markup rendered as elements and components) through the [extensions](#extensions) pipe - ๐ **TypeScript** โ Complete type definitions, with keys and payloads typed by a schema registered once for the whole app, generated by [`@sveltekit-i18n/typegen`](https://github.com/sveltekit-i18n/typegen), and read as members of `t` with [`extension-typed-access`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) - ๐จ **Component-scoped** โ Create multiple translation instances for different parts of your app ## Requirements Svelte 5 or newer, and one of Node 22+, Bun 1.2+ or Deno 2+. The package is ESM-only and imports no `node:` module, so every runtime that runs your SvelteKit build runs it. The docs' SvelteKit snippets need SvelteKit 2.12 or newer, which ships `$app/state`; `@sveltekit-i18n/typegen` needs Vite 8, which SvelteKit supports from 2.53, and so Node 22.12 or newer. ## Installation In a SvelteKit 3 project that does not use sveltekit-i18n yet, the [Svelte CLI add-on](https://github.com/sveltekit-i18n/sv) sets it up for you. It asks for your locales, the message format, the routing, the extensions, typed keys and a demo page, then installs the packages and writes what the Quick Start below walks through: the translations, `src/lib/i18n`, the hooks, the layouts and `app.html`. ```bash npx sv add @sveltekit-i18n ``` To install it by hand instead: ```bash npm install sveltekit-i18n # bun add sveltekit-i18n # deno add npm:sveltekit-i18n ``` That is the whole install. `@sveltekit-i18n/base` and `@sveltekit-i18n/parser-curly` come with it: the core's whole API, the parser's types and its build-time `extractParamsFactory` and `cst` are re-exported here โ **do not install them alongside**, or your app ends up with two copies of the core and two reactive graphs. ## Quick Start ### 1. Create your translation files ```jsonc // src/lib/translations/en/common.json { "greeting": "Hello, {{name}}!", "nav.home": "Home", "nav.about": "About" } ``` ```jsonc // src/lib/translations/cs/common.json { "greeting": "Ahoj, {{name}}!", "nav.home": "Domลฏ", "nav.about": "O nรกs" } ``` ### 2. Define the config and wire it ```javascript // src/lib/i18n.js import { defineI18n } from 'sveltekit-i18n/kit'; /** @satisfies {import('sveltekit-i18n').Config} */ export const config = { initLocale: 'en', loaders: [ { locale: ['en', 'cs'], namespace: 'common', loader: async ({ locale, namespace }) => (await import(`./translations/${locale}/${namespace}.json`)).default, }, ], }; export const { handle, load, use, get } = defineI18n(config, { preferredLocale: (event) => event.cookies?.get('lang'), }); ``` A loader descriptor may list several locales and namespaces; the loader is called once per pair, with the pair in its props. No parser is stated: this package fills that slot. ### 3. Hook it into SvelteKit `#lib` is the `imports` entry `sv create` scaffolds in a SvelteKit 3 app's `package.json`. A SvelteKit 2 app adds the same entry, `"imports": { "#lib/*": "./src/lib/*" }`, or imports from `$lib/i18n` โ as it must on Vite 5 when `i18n` is a `.ts` file imported from a `.js` module or a plain ` {@render children()} ``` ```html ``` The server negotiates the locale on every request โ `preferredLocale`, then `Accept-Language`, then `initLocale`, `fallbackLocale` and the first locale the config serves โ loads it into an instance of its own and hands its state to the browser, which keeps one instance per tab and does not fetch again what the server loaded. `handle` fills `%lang%` and `%dir%`. ### 4. Use translations in your components ```svelte
{i18n.t('welcome', { name: 'Alice' })}
{i18n.t('items', { count: 5 })}
``` The syntax is the [Curly Message Format](https://curlymessage.dev). Its parser options โ custom modifiers, modifier defaults, a report channel and how payload values are read โ go under `config.parserOptions`: ```javascript const config = { parserOptions: { modifierDefaults: { number: { maximumFractionDigits: 2 } }, onReport: (report) => console.warn(report.message, report), }, loaders: [/* โฆ */], }; ``` Reports are silent by default; `onReport` is where you route them. ### Server-side rendering `sveltekit-i18n/kit` builds one instance **per request** on the server โ a module-level instance is shared between concurrent requests, which leaks one visitor's locale into another's page โ and hands its state to the browser. The [API documentation](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#sveltekit) covers how it picks the locale and what to watch for. Wiring it by hand takes the same two halves: the server returns `snapshot({ records: true })`, which carries the data and the loaders that delivered it, and the client applies it with `hydrate()`, so those loaders do not run again: ```javascript // src/routes/+layout.server.js import { I18n } from 'sveltekit-i18n'; import { config } from '#lib/i18n.js'; export const load = async ({ url, locals }) => { const i18n = new I18n(config); await i18n.loadTranslations(locals.locale, url.pathname); return { i18n: i18n.snapshot({ records: true }) }; }; ``` ```javascript // src/routes/+layout.js, where the instance is built i18n.hydrate(data?.i18n); ``` Data passed to `addTranslations()` or `config.translations` only seeds the tables: it keeps no loader from running. The full manual recipe is in [Server-Side Rendering](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#server-side-rendering). ### Base path An app served under SvelteKit's `paths.base` sets the same value as `config.basePath`, so loader `routes` keep naming the app's own paths (`/about`, not `/repo/about`). ### Utilities `sveltekit-i18n/utils` publishes the helpers the core uses where application code has to match it โ `sanitizeLocales`, `toDotNotation`, `resolveLoaders` โ and two for choosing and writing a locale: `matchLocale` (`Accept-Language`, `navigator.languages` or a cookie against the configured set) and `textDirection` (`'ltr'` or `'rtl'`). ## Upgrading from 3.3 A 3.3 config loads in 3.4 as it is. What to check: - **A `sveltekit-i18n/kit` navigation shows its data at commit.** Its `load` now preloads the target with `preload()`, and the commit shows what that fetched, so a `cache: false` loader runs once per navigation instead of twice, and neither it nor an elapsed `cache` window leaves the page on the previous page's text until a refetch at commit lands; a `cache: false` loader whose fetch the preload only shared is refreshed behind what it shows. A preload is a request, a hover's included, so it ends the pass a `hydrate()` hand-off held a `cache: false` loader back for. - **A hand-wired app should stop activating a preload.** The 3.3 docs' SSR recipe called `loadTranslations()` on every pass of the universal `load`, which SvelteKit runs for a hover's preload too, so hovering a link switched the instance before the click. Follow the updated recipe: only the pass that builds the instance activates, every later pass calls `preload()`, and the root layout commits the navigation ([steps 3 and 4](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#3-build-the-instance-the-application-renders-with)). A [singleton](#without-a-server) whose `load` calls `loadTranslations()` makes the same change. An instance piped through [`extension-stores`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) carries `preload()` from extension-stores 3.2. `sveltekit-i18n/kit` needs none. - **A page render builds one instance.** The universal `load` of a page render takes over the instance the server `load` loaded instead of hydrating a second one from its snapshot, unless a loader has `cache: false`. A wrapper that copies `data.i18n` still builds the second one; pass it on as the object it is ([Combining with your own code](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#combining-with-your-own-code)). - **A call whose data cannot be applied is undone.** When a custom `preprocess` throws on what a call's load brought, the call is undone as one whose loader threw SvelteKit's control flow, its route aside, and it never throws synchronously. - **Schema-typed calls check fast.** A `t` or `l` call on a key of the schema costs the checker the same at any schema size, a key outside it or a union of many keys no longer stalls an editor for minutes, and a wrapper typed with `Schema.Key` and `Schema.Params` is assignable to `t` and `l` both ways. - **Large catalogues load in linear time**, at the cost, on Node and Deno, of slower listing and serializing and more memory per instance for tables of up to about a thousand keys; see [base's notes](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-32). A custom `preprocess` is called once per rebuilt locale on a re-delivery, with the whole table. - **A namespace holding `NaN` travels in the snapshot** instead of being left out with a warning. - **A `date` placeholder whose layers name no `timeZone`** keeps the zone the host had when its formatter was built, since the formatting modifiers now keep their `Intl` objects. - **`sveltekit-i18n/kit` takes the params a SvelteKit 3 matcher parsed** (3.4.1). Up to 3.4.0, `handle` and `load` typed every param as a string, so under SvelteKit 3 one matcher that parses a param made `handle: Handle = handle`, `sequence(handle)` and a typed wrapper calling `load` fail to compile. A member an app implements against `Kit.T` now reads its event's params as `any` unless it annotates the event with `Kit.ParamValue`, a param as SvelteKit 3 types it ([Which locale](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md#which-locale)). A copy of the core inside the app root and outside its `node_modules` no longer fails a SvelteKit 3 build as a server-only import. - **New:** `preload(locale, route?)`, `{ preloaded }` on `loadTranslations()` and `setRoute()`, and `Loader.Preloaded`; in 3.4.1, `Kit.ParamValue` and a params type parameter on `Kit.Event` and the event types built on it. - **Companion releases.** [`extension-typed-access`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) 3.0.0 is new: keys as members of `t`, `t.home.title()`. [`extension-html`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-html) 3.0 is new: a `T` component that renders the markup a message carries as elements and Svelte components, without `{@html}`. [`extension-stores`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) 3.2.0 passes `preload()` through and, in a component mounted after the stores start following the instance, re-renders a `$t(...)` once per change instead of twice. [`@sveltekit-i18n/typegen`](https://github.com/sveltekit-i18n/typegen) 3.1.0 also registers the keys nested by segment, which typed access reads instead of grouping them on every compile, and accepts SvelteKit 3. [`parser-icu`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-icu) and [`parser-mf2`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-mf2) 3.1.0 take a `cacheLimit` option; `parser-icu` moves to `intl-messageformat` 12, and its `extractParamsFactory` reads a message with the parser that compiles it. It and [`parser-i18next`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-i18next) 3.0.4 keep their `Intl` formatters, so a date that names no `timeZone` keeps the zone the host had when its formatter was built. `extension-html` 3.0.2 renders every attribute but `title` without the bidi controls MF2 isolates a placeholder with and `Intl` marks a number with, so a link built from one keeps its URL. The core's notes: [base โ Upgrading from 3.2](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-32), and the parser's in [parser-curly's changelog](https://github.com/sveltekit-i18n/parsers/blob/master/parser-curly/CHANGELOG.md#321). ## Upgrading from 3.2 A 3.2 config loads in 3.3 as it is. What to check: - **A pass always has a locale when the config serves one.** When neither what the visitor prefers, `initLocale` nor `fallbackLocale` names a served locale, `sveltekit-i18n/kit` now takes the first locale the config serves (the loaders' locales in config order, then the `translations` keys) instead of rendering without one. Set `initLocale` to choose the locale such a visitor gets. The core's notes: [base โ Upgrading from 3.1](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-31). ## Upgrading from 3.1 A 3.1 config loads in 3.2 as it is. What to check: - **`plural` and `ordinal` join the built-in modifiers**, which select an option by the locale's plural rules: `{{count:plural; one:item; other:items;}}`. A custom modifier registered under either name still replaces the built-in one. - **A generated schema types a plural selection's count as a number**, since `extractParamsFactory` reports the parameter a selection reads as `'number'`. - **A seed stays over what a loader delivered before it**: data added with `addTranslations()`, `config.translations` or a plain `hydrate()` is no longer put back under that delivery when a sibling loader delivers again and the namespace is rebuilt, until that loader delivers again itself. The parser's notes are in [parser-curly's changelog](https://github.com/sveltekit-i18n/parsers/blob/master/parser-curly/CHANGELOG.md#320). ## Upgrading from 3.0 A 3.0 config loads in 3.1 as it is. What to check: - **Messages follow version 3 of the Curly Message Format.** A payload value is data and is never read as syntax, so a catalogue that composed messages through its payload, or that doubled backslashes in values, renders differently; `parserOptions.onSuspectValue` announces every such value while you migrate. `pass-limit` is gone from `Report['code']`. - **Seeds no longer count as loaded.** A client that applied the server's `snapshot()` with `addTranslations()` now fetches everything again after hydration โ move to `sveltekit-i18n/kit`, or to `snapshot({ records: true })` with `hydrate()`. - **A loader's `key` is now `namespace`.** `key` still works and logs a deprecation warning once per loader; it goes in the next major. - **SvelteKit's `redirect()` and `error()` below 500**, thrown from a loader, reject the load instead of failing soft. - **Named capture groups in route `RegExp`s are route params**, and each loader of a namespace is recorded on its own. The whole list is in [base's upgrade notes](https://github.com/sveltekit-i18n/base/blob/master/docs/README.md#upgrading-from-30), and the format's move in [parser-curly's changelog](https://github.com/sveltekit-i18n/parsers/blob/master/parser-curly/CHANGELOG.md#310). ## Documentation **๐ [sveltekit-i18n.github.io](https://sveltekit-i18n.github.io)** โ The documentation site, with a live playground **๐ [Complete Documentation Index](https://github.com/sveltekit-i18n/lib/blob/master/docs/INDEX.md)** โ Find everything in one place ### Quick Links - ๐ [Getting Started Guide](https://github.com/sveltekit-i18n/lib/blob/master/docs/GETTING_STARTED.md) โ 15-minute tutorial - ๐๏ธ [Architecture Overview](https://github.com/sveltekit-i18n/lib/blob/master/docs/ARCHITECTURE.md) โ How everything works - ๐ [API Documentation](https://github.com/sveltekit-i18n/lib/blob/master/docs/README.md) โ Complete reference - โจ [Best Practices](https://github.com/sveltekit-i18n/lib/blob/master/docs/BEST_PRACTICES.md) โ Production-ready patterns - ๐ง [Troubleshooting](https://github.com/sveltekit-i18n/lib/blob/master/docs/TROUBLESHOOTING.md) โ Common issues & FAQ ## Examples Each example is a standalone SvelteKit application covering a decision that is application-shaped โ an adapter, a `vite.config.ts`, a route tree: - [Multi-page app](https://github.com/sveltekit-i18n/lib/tree/master/examples/multi-page) โ the common setup: cookie and `Accept-Language`, route-scoped loading - [Locale-based routing](https://github.com/sveltekit-i18n/lib/tree/master/examples/locale-router) โ SEO-friendly URLs (e.g. `/en/about`), prerendered - [Default locale without a prefix](https://github.com/sveltekit-i18n/lib/tree/master/examples/locale-router-advanced) โ `/about` and `/cs/about`, static, translated 404 - [Component-scoped translations](https://github.com/sveltekit-i18n/lib/tree/master/examples/component-scoped-ssr) โ a component with its own lexicon - [Markdown routes](https://github.com/sveltekit-i18n/lib/tree/master/examples/mdsvex) โ `t()` inside `.svx` - [Stores](https://github.com/sveltekit-i18n/lib/tree/master/examples/stores) โ the `$t` store surface, through `extension-stores` - [Typed access](https://github.com/sveltekit-i18n/lib/tree/master/examples/typed-access) โ keys as members of `t`, through `extension-typed-access` - [HTML](https://github.com/sveltekit-i18n/lib/tree/master/examples/html) โ markup in a message rendered as elements, through `extension-html` - [All examples](https://github.com/sveltekit-i18n/lib/tree/master/examples) โ complete list Everything that is really three lines of configuration โ message formats, `preprocess`, `loaders`, `fallbackLocale` โ is on the [playground](https://sveltekit-i18n.github.io/playground) instead, where a real instance answers as you change it. ## Advanced Usage ### Need a different parser? This package wires `@sveltekit-i18n/parser-curly` and fills the core's `parser` slot itself, so a different message format means building on [@sveltekit-i18n/base](https://github.com/sveltekit-i18n/base) directly: ```javascript import { I18n } from '@sveltekit-i18n/base'; import parser from '@sveltekit-i18n/parser-icu'; const config = { parser: parser({ onReport: null }), // ... rest of config }; ``` That is the one case where installing the core directly is right โ you are then not using this package at all. The same goes for [`parser-mf2`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-mf2) (Unicode MessageFormat 2) and [`parser-i18next`](https://github.com/sveltekit-i18n/parsers/tree/master/parser-i18next) (the i18next syntax). Learn more about [parsers](https://github.com/sveltekit-i18n/parsers). ### Extensions `config.extensions` pipes the constructed instance through adapter functions, left to right, and `new I18n(config)` evaluates to the last one's output. That is how the store surface ships: ```javascript import { I18n } from 'sveltekit-i18n'; import stores from '@sveltekit-i18n/extension-stores'; export const { t, locale, loading } = new I18n({ ...config, extensions: [stores] }); ``` The official extensions, each installed on its own: - [`@sveltekit-i18n/extension-stores`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-stores) โ the Svelte store surface v2 had: `$t`, `$locale`, `$loading` - [`@sveltekit-i18n/extension-typed-access`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-typed-access) โ keys as members of `t`, `t.home.title()` beside `t('home.title')`, typed from the schema - [`@sveltekit-i18n/extension-html`](https://github.com/sveltekit-i18n/extensions/tree/master/extension-html) โ a `T` component that renders the markup a message carries as elements and Svelte components, without `{@html}` The order matters. `extension-stores` returns no instance, so it goes after the other two: `[typedAccess, stores]` hands out `$t.home.title()`, and `[html({ onReport: null }), stores]` puts `T` at `instance.T`. `extension-html` goes after `extension-typed-access`, and adds `T` beside the member keys. ## TypeScript Support Full TypeScript support with complete type definitions for configuration and API: ```typescript import { I18n, type Config } from 'sveltekit-i18n'; const config: Config = { loaders: [ // ... your loaders ], }; export const i18n = new I18n(config); ``` Annotating the config (`const config: Config = โฆ`) widens it, which costs the locale completion a config literal would have given `setLocale` and `l`. Pass the literal straight to the constructor where you want that. To have keys and payloads checked, type the instance with a schema โ keys autocomplete and a wrong payload is a type error. The app registers one schema for every instance (see [Generating the schema](#generating-the-schema)), or a config states its own: ```typescript import { I18n } from 'sveltekit-i18n'; const i18n = new I18n({ ...config, schema: {} as { 'common.greeting': { name: string } }, }); i18n.t('common.greeting', { name: 'Alice' }); // ok i18n.t('common.greting', { name: 'Alice' }); // Error: not a key of the schema i18n.t('common.greeting', {}); // Error: `name` is required ``` Only the schema's **type** is read, so the slot may hold an empty value. A single payload type for every message is stated through the type arguments instead: ```typescript import { I18n, type Config } from 'sveltekit-i18n'; type Payload = { name: string }; const config: Config