i18n
Translations for the frontend and the server from one set of JSON files, with typed functions on both sides. A missing key or a mismatched parameter in any language fails the build, so translations can't drift. Numbers, money and dates are formatted the same way in the browser and in Kotlin.
Gradle Generated files Ktor pluginThis page is part of Frontend libraries.
Quick start
svelte {
libraries {
i18n {
locales("en", "de")
}
}
}{
"app-title": "Notes",
"server-greeting": "Hello {name}, greetings from Ktor!"
}<script lang="ts">
import { m } from '#i18n';
</script>
<h1>{m.appTitle()}</h1>
<p>{m.serverGreeting({ name: 'Ada' })}</p>Settings
import io.github.nijasc.ktor.svelte.gradle.LocaleStrategy
svelte {
libraries {
i18n {
locales("en", "de")
defaultLocale = "en"
strategy = LocaleStrategy.Cookie
}
}
}| Setting | Default | What it does |
|---|---|---|
locales(...) | required | The languages, as tags such as en, de or pt-BR |
defaultLocale | The first locale | The language when nothing else decides, and the one the other files are compared with |
strategy | LocaleStrategy.Cookie | How the language is chosen and kept, see Strategies |
messagesDir | frontend/messages | The folder with one JSON file per language |
The build stops when there is no locale, when defaultLocale is not one of the locales, or when a locale is not a tag such as en or pt-BR.
Message files
Keep one JSON file per language in frontend/messages, such as en.json and de.json. svelteInit creates an empty file for every locale you configured, and never touches one that is already there. Files are flat, and {name} is a parameter:
{
"server-greeting": "Hello {name}, greetings from Ktor!",
"app-title": "Notes"
}- Each key becomes a function named in camel case:
app-titleism.appTitle()in TypeScript andappTitle()in Kotlin. - Every key must exist in every file, with the same parameters. Otherwise the build fails and names the key.
- Parameters are plain text replacements. For "1 note" and "2 notes", use plurals.
In Svelte
<script lang="ts">
import { getLocale, localizeHref, locales, m, setLocale } from '#i18n';
</script>
<h1>{m.appTitle()}</h1>
<p>{m.serverGreeting({ name: 'Ada' })}</p>
<a href={localizeHref('/about')}>About</a>
<button onclick={() => setLocale('de')}>Deutsch</button>| Export | What it is |
|---|---|
m | One function per message, typed with its parameters |
locales | The configured locales, in order |
Locale | The union of those locales, such as 'en' | 'de' |
defaultLocale | The default locale |
getLocale() | The current visitor's locale |
setLocale(locale) | Saves the locale and shows the page in it. With cookies the page reloads, with URL prefixes it goes to the same page under the new prefix |
localizeHref(path) | The path with the locale prefix when that strategy is on, and unchanged otherwise |
In Kotlin
import io.github.nijasc.ktorsvelte.Messages
import io.github.nijasc.ktorsvelte.messages
get("/api/hello") {
call.respondText(call.messages.serverGreeting("Ada"))
}
val german = Messages.forLocale("de").appTitle()| Name | What it is |
|---|---|
call.messages | The messages in the visitor's language |
Messages.forLocale(locale) | The messages in another language, for an email to someone else. An unknown locale gives the default one |
Messages.locales, Messages.defaultLocale | The configured locales |
call.svelteLocale | The visitor's locale as text, from io.github.nijasc.ktor.svelte |
call.localizeHref(path) | Like localizeHref, for redirects from Ktor |
call.formats | Formats in the visitor's language |
call.emails | Emails in the visitor's language, when the app has email components |
Messages make server errors readable in the visitor's language:
post("/api/register") {
if (users.isTaken(email)) {
return@post call.respond(HttpStatusCode.Conflict, Problem(call.messages.problemEmailTaken()))
}
}Strategies
Choose how the language is picked with strategy:
| Strategy | URLs | Best for | Trade-off |
|---|---|---|---|
Cookie (default) | /about | Apps behind a login | Prerendered pages hold the default language and switch on load, so others can flash briefly, and search engines mostly see one language |
UrlPrefix | /de/about | Public sites and SEO | Every language gets its own prerendered pages. Plain paths redirect to the visitor's language. Links must use localizeHref, or typed routes, or pages won't be prerendered per language |
Cookie
import io.github.nijasc.ktor.svelte.gradle.LocaleStrategy
svelte {
libraries {
i18n {
locales("en", "de")
strategy = LocaleStrategy.Cookie
}
}
}URLs stay as they are. setLocale saves the choice in a cookie for a year and reloads the page.
URL prefix
import io.github.nijasc.ktor.svelte.gradle.LocaleStrategy
svelte {
libraries {
i18n {
locales("en", "de", "fr")
strategy = LocaleStrategy.UrlPrefix
}
}
}Every page lives under its language, such as /de/about. ktor-svelte generates src/hooks.ts for the prefixes. Write links through localizeHref or typed routes:
<script lang="ts">
import { localizeHref } from '#i18n';
</script>
<a href={localizeHref('/about')}>About</a>How the language is chosen
On the server, call.svelteLocale and call.messages follow the same rules as the browser:
- The URL prefix, if that strategy is on.
- The cookie.
Accept-Language.- Your default locale.
localizeHref is safe with either strategy, and call.localizeHref does the same for redirects from Ktor.
Live reload while developing
While svelteDevAll or svelteDev runs, saving a message file updates the frontend functions at once, and Vite reloads them, with no Gradle run. Under svelteDevAll the Kotlin Messages follow and the app restarts. With svelteDev alone, they update the next time Kotlin compiles. A file with a missing key or a mismatched parameter is reported in the console, and the last good version stays until you fix it.
Plurals
"1 note" and "2 notes" are one message with two forms, and how many forms there are depends on the language. Write the forms into the message:
{
"notes-count": "{count, plural, =0 {No notes} one {# note} other {# notes}} in {folder}"
}# stands for the number. The generated functions take the count as a number and pick the form for the current language, in TypeScript and in Kotlin alike:
m.notesCount({ count: notes.length, folder: 'Inbox' });call.messages.notesCount(notes.size, "Inbox")- The forms are
zero,one,two,few,manyandother. A language uses only some of them: English and Germanoneandother, Russian and Polishone,few,manyandother, Japanese onlyother. Every plural needsother. =0,=1and so on match one exact number, before the forms of the language. That is how "No notes" is written.- A form can hold other placeholders, and another plural.
- Counts are whole numbers.
The same message in German:
{
"notes-count": "{count, plural, =0 {Keine Notizen} one {# Notiz} other {# Notizen}} in {folder}"
}svelteSync checks the messages: a plural without other, a form the language of that file never uses, a form name that does not exist, or a count in one language that is plain text in another all stop it with the key named.
In the browser the choice of form comes from Intl.PluralRules. In Kotlin it comes from rules that are generated for the configured languages, checked against the browser's for the languages the plugin knows: the western and northern European ones, the Slavic and Baltic ones, Romanian, Hebrew, Arabic, and those without plural forms such as Japanese, Chinese and Korean. A language outside that list is treated like English in Kotlin.
Numbers, money and dates
A price on the page and the same price in an email from the server should read the same. With toLocaleString in the browser and NumberFormat on the JVM they often do not: the two carry different versions of the locale data, and disagree about spaces, month names and where the currency sign goes.
With i18n on, both sides get the same five functions, generated from one table for the configured languages. In TypeScript they come from #format, in Kotlin from call.formats:
import { formatDate, formatDateTime, formatMoney, formatNumber, formatTime } from '#format';
formatNumber(1234567.891, 2); // 1,234,567.89 or 1.234.567,89
formatMoney(order.total, 'EUR'); // the euro sign and 1,234.50, in the order the language uses
formatDate(note.dueOn); // Mar 7, 2026 or 07.03.2026
formatDateTime(note.createdAt); // Dec 24, 2026, 3:05 PM
formatTime(note.createdAt);val formats = call.formats
formats.formatMoney(order.total, "EUR")
formats.formatDate(note.dueOn)
formats.formatDateTime(note.createdAt, call.timeZone)What is supported, and nothing else, so the two sides cannot drift apart:
| Function | Input | Output |
|---|---|---|
formatNumber(value, decimals = 0) | A number, or decimal text such as a Decimal | Grouped in threes, rounded half up to exactly decimals places. |
formatMoney(amount, currency) | As above, and a currency code | The sign and decimal places of the currency for 37 common currencies, the code and two places for others. |
formatDate(value, style) | An ISO date, or a Date. In Kotlin a LocalDate | short (3/7/26), medium (Mar 7, 2026, the default) or long (March 7, 2026). |
formatDateTime(value, style) | An ISO date-time, or a Date. In Kotlin an Instant and a ZoneId | short or medium date with the time in hours and minutes. |
formatTime(value) | As above | Hours and minutes, with AM and PM where the language uses them. |
Date styles
formatDate(note.dueOn, 'short'); // 3/7/26
formatDate(note.dueOn, 'medium'); // Mar 7, 2026
formatDate(note.dueOn, 'long'); // March 7, 2026
formatDateTime(note.createdAt, 'short');In Kotlin the style is the generated DateStyle enum: DateStyle.Short, DateStyle.Medium and DateStyle.Long.
Another language or time zone
- The language is the visitor's, as for messages. Every function takes a locale as its last argument in TypeScript, and
Formats.forLocale(...)gives another one in Kotlin. - Dates and times are printed in the browser's time zone in TypeScript. In Kotlin you pass the zone, and
call.timeZoneis the visitor's.
formatMoney(invoice.total, 'CHF', 'de');val forCustomer = Formats.forLocale(customer.locale)
forCustomer.formatDateTime(invoice.sentAt, ZoneId.of("Europe/Zurich"), DateStyle.Short)What is covered
- The table covers 64 locales. A region without its own entry uses its language, and a language that is not in the table is formatted like English.
- Not covered: weekday names, seconds, time zone names, compact numbers such as 1.2K, percent, and digits other than 0 to 9. For those, format on one side only.
- The data comes from the JDK's copy of the Unicode locale data and is fixed in each plugin version, so a new JDK or browser does not change what your app prints.
Relative time
timeAgo from #format tells a time as its distance from now, in the visitor's language: "now", "3 minutes ago", "yesterday", "in 2 hours". It is for the browser only and uses the browser's own words, through Intl.RelativeTimeFormat:
import { timeAgo } from '#format';
timeAgo(note.createdAt);It also takes the moment to count from and a locale: timeAgo(value, now, locale).
Text made once goes stale while the page stays open. With components(), <TimeAgo value={note.createdAt} /> keeps itself current: it renders a <time> element with the exact date and time as its tooltip, and every instance on the page is refreshed by one shared timer, twice a minute.
Messages nobody translated yet
A key has to exist in every language file, or the build fails. The quick way to get past that is to paste the English text into the other files and translate later, and "later" is easy to forget. In development the dev panel shows a Not translated section whenever you look at the app in another language than the default one. It lists every message on the page whose text is the same as in the default language, with its key.
Tick Outline them on the page and those texts get a dashed outline where they appear, so you see what a visitor in that language would read in the wrong one. The choice is remembered in your browser.
Some words are the same in two languages on purpose, such as "Name" or "Status" in English and German. They are listed too, which is why the outline is off until you ask for it.
Messages nothing uses
A missing message fails the build, but one that is no longer used stays in every locale file and keeps being translated. svelteVerifyMessages lists them:
./gradlew svelteVerifyMessagesold-banner -> nothing calls oldBanner() and no source names 'old-banner'A message counts as used when its generated function is called anywhere in the frontend or in Kotlin, or when its key appears as a string, because it may then be looked up by name. The task only lists what it finds. Add --strict to fail the build instead:
./gradlew svelteVerifyMessages --strictLocaleSwitch
With components() on, LocaleSwitch is a ready-made language select. It lists each language under its own name, such as English and Deutsch, and switches with setLocale:
<script lang="ts">
import LocaleSwitch from '#components/LocaleSwitch.svelte';
import { m } from '#i18n';
</script>
<LocaleSwitch label={m.settingsLanguage()} />Translating built-in texts
Some generated pieces bring English texts of their own. Translate them like this:
| Piece | How |
|---|---|
| Error page | Add the error-... keys to your messages |
| Offline page | Add offline-title, offline-text and offline-retry |
| Toasts | Set toastMessages once at startup |
| Confirm dialog | Set confirmMessages once at startup |
| Components | Pass label, labels and the text props, such as empty on DataTable |
Full example
An account page in two languages: a plural, money and dates formatted in the visitor's language, and a relative time. The server sends a receipt email with the same formats, in the customer's language rather than the visitor's.
{
"account-title": "Your account",
"account-orders": "{count, plural, =0 {No orders yet} one {# order} other {# orders}}",
"account-spent": "Spent so far: {amount}",
"account-member-since": "Member since {date}",
"receipt-subject": "Your order from {date}",
"receipt-total": "Total: {amount}"
}{
"account-title": "Dein Konto",
"account-orders": "{count, plural, =0 {Noch keine Bestellungen} one {# Bestellung} other {# Bestellungen}}",
"account-spent": "Bisher ausgegeben: {amount}",
"account-member-since": "Mitglied seit {date}",
"receipt-subject": "Deine Bestellung vom {date}",
"receipt-total": "Summe: {amount}"
}<script lang="ts">
import LocaleSwitch from '#components/LocaleSwitch.svelte';
import TimeAgo from '#components/TimeAgo.svelte';
import { formatDate, formatMoney } from '#format';
import { m } from '#i18n';
import type { PageProps } from './$types';
let { data }: PageProps = $props();
</script>
<svelte:head>
<title>{m.accountTitle()}</title>
</svelte:head>
<div class="mb-6 flex items-center justify-between">
<h1 class="text-3xl font-bold">{m.accountTitle()}</h1>
<LocaleSwitch />
</div>
<p>{m.accountMemberSince({ date: formatDate(data.account.createdAt, 'long') })}</p>
<p>{m.accountOrders({ count: data.orders.length })}</p>
<p>{m.accountSpent({ amount: formatMoney(data.account.spent, 'EUR') })}</p>
<ul class="mt-6 grid gap-2">
{#each data.orders as order (order.id)}
<li class="flex justify-between">
<span>{formatMoney(order.total, order.currency)}</span>
<TimeAgo value={order.placedAt} class="opacity-70" />
</li>
{/each}
</ul>import io.github.nijasc.ktorsvelte.DateStyle
import io.github.nijasc.ktorsvelte.Formats
import io.github.nijasc.ktorsvelte.Messages
fun receiptEmail(order: Order, customer: Customer): Email {
val messages = Messages.forLocale(customer.locale)
val formats = Formats.forLocale(customer.locale)
val placed = formats.formatDateTime(order.placedAt, customer.zone, DateStyle.Short)
return Email(
to = customer.email,
subject = messages.receiptSubject(placed),
text = messages.receiptTotal(formats.formatMoney(order.total, order.currency)),
)
}The page and the email print the same amount and date the same way, because both come from the same table.
Use cases
- An app behind a login, used in a few languages: the default
Cookiestrategy. - A public site where each language should be found by search engines:
UrlPrefix. - Prices, invoices and dates that must read the same on the page and in emails:
#formatandcall.formats. - Error messages from the server in the visitor's language:
call.messagesin aProblem. - Keeping message files clean:
svelteVerifyMessages.
Good to know
The build guards the files
A missing key, a mismatched parameter or a broken plural in any language fails the build, with the key named.
Prerendered pages with cookies
With the Cookie strategy, prerendered pages hold the default language and switch on load. Use UrlPrefix when that brief flash, or search engines seeing one language, matters.
Where the generated files are
src/lib/ktor-svelte/i18n.ts (#i18n) and src/lib/ktor-svelte/format.ts (#format) in the frontend, and Messages, Formats and the call.messages and call.formats extensions in the generated Kotlin package.