# ktor-svelte 1.4.0
> Ship a Ktor API and a SvelteKit frontend as one app: one JAR, one port, and a TypeScript client that matches your routes.
Source: https://nijasc.github.io/ktor-svelte/guide/introduction
# What is ktor-svelte?
ktor-svelte turns a Ktor API and a SvelteKit frontend into one application. In production it is a single JAR on a single port. In development you open Ktor's port and get Vite's hot reload.
It comes in parts that work together:
| Part | Artifact | What it does |
|---|---|---|
| Ktor plugin | `ktor-svelte-server` | `install(Svelte)` serves the frontend next to your API, adds the security and caching defaults, and writes the TypeScript client |
| Gradle plugin | `io.github.nijasc.ktor-svelte` | Builds the frontend into the JAR, runs the dev loop, sets up frontend libraries, and checks that generated files are current |
| Generated client | `frontend/src/lib/api` | Types, services and validation helpers for every Ktor route, imported as `#api`, with no npm dependencies |
| Test kit | `ktor-svelte-test` | Kotlin tests that drive a real browser against the packaged app |
## In 30 seconds
Install the plugin in Ktor:
```kotlin
install(Svelte) {
generateTs = true
transport {
json()
}
}
```
Write a route in Kotlin, save, and call it from Svelte with full types:
```ts
import { api } from '#api';
const note = await api.notes.create({ title: 'Buy milk' });
```
Then build one JAR that holds both:
```bash
./gradlew buildFatJar
```
**Made with AI**
This project was made heavily with AI, and nothing is guaranteed. It has real tests, but read the code before you trust it with anything important. Since 1.0, releases follow semantic versioning, so only a major release can break your build.
## How the pieces fit
```text
frontend/ SvelteKit with adapter-static
src/main/kotlin/ your Ktor app with install(Svelte)
build.gradle.kts the ktor-svelte Gradle plugin
```
1. **At build time**, the Gradle plugin installs your frontend dependencies, runs the SvelteKit build and copies the static output into the JAR, together with a manifest that lists every file and its hash.
2. **At run time**, `install(Svelte)` serves those files on the same port as your API. Your Ktor routes always win, missing pages get the SPA fallback, and hashed assets are cached forever.
3. **In development**, the plugin proxies page requests to Vite, so you get hot reload on Ktor's port with the same origin as production, and the TypeScript client is regenerated from your routes whenever the app starts.
The frontend is plain files, so there is no Node process in production. SvelteKit runs in the browser, and Ktor is the only backend. The [FAQ](https://nijasc.github.io/ktor-svelte/reference/faq) explains why ktor-svelte uses `adapter-static` and what that means for server-side rendering, and [How it works](https://nijasc.github.io/ktor-svelte/reference/how-it-works) follows a request through the app.
## What you get
- **One port, one JAR.** Works with `jar`, Shadow and Ktor's `buildFatJar`.
- **Your routes win.** Anything you define in Ktor beats the frontend, whatever order you register it in.
- **Generated TypeScript.** Types, services, validation rules and typed errors from your Ktor routes, with no npm dependencies. See [Generated TypeScript](https://nijasc.github.io/ktor-svelte/features/typescript).
- **Real hot reload.** One command runs Vite, the Kotlin compiler and your app. See [Dev workflow](https://nijasc.github.io/ktor-svelte/guide/dev-workflow).
- **Secure defaults.** CSP, security headers, origin check, body and rate limits, hidden error details. See [Security](https://nijasc.github.io/ktor-svelte/security).
- **Fast defaults.** Immutable caching, ETags, precompressed files, compressed API responses, real 404s for stale chunks. See [Transport and compression](https://nijasc.github.io/ktor-svelte/features/transport).
- **Frontend libraries from Kotlin.** Tailwind, DaisyUI, Lucide, i18n, image optimization and error toasts, configured in Gradle. See [Frontend libraries](https://nijasc.github.io/ktor-svelte/features/frontend-libraries).
- **Any package manager.** Bun, pnpm, npm or Yarn, picked from your lockfile.
- **IntelliJ run configurations.** One click starts everything.
The full list, grouped by what you are doing, is on [Everything ktor-svelte does](https://nijasc.github.io/ktor-svelte/features).
## Is it for you?
It fits well when:
- the backend is, or should be, on the JVM, and you want a SvelteKit frontend with it,
- you want to deploy one artifact and run one process,
- you want the frontend to break at compile time, not in production, when an API changes.
Look elsewhere when you need server-side rendering on every request, or when the frontend and backend are deployed by different teams. [Compared with other setups](https://nijasc.github.io/ktor-svelte/guide/comparison) goes through the alternatives.
## Where to go next
- New project: [Getting started](https://nijasc.github.io/ktor-svelte/guide/getting-started)
- Learn by building: [Tutorial](https://nijasc.github.io/ktor-svelte/guide/tutorial)
- Existing Ktor or SvelteKit app: [Add to an existing project](https://nijasc.github.io/ktor-svelte/guide/existing-project)
- See it working first: [Examples](https://nijasc.github.io/ktor-svelte/examples)
- Deciding between setups: [Compared with other setups](https://nijasc.github.io/ktor-svelte/guide/comparison)
- Asking an AI assistant: give it [llms-full.txt](https://nijasc.github.io/ktor-svelte/llms-full.txt), the whole documentation as one Markdown file, or the index at [llms.txt](https://nijasc.github.io/ktor-svelte/llms.txt)
Source: https://nijasc.github.io/ktor-svelte/guide/getting-started
# Getting started
Create a new Ktor and SvelteKit project with everything wired up, and run it. It takes one command and a couple of minutes.
## What you need
- Java 17 or newer
- One of Bun, pnpm, npm or Yarn on your `PATH`
That is all. The setup script brings its own Gradle wrapper and always uses the latest ktor-svelte release.
## 1. Create the project
**macOS and Linux:**
```bash
curl -fsSL https://raw.githubusercontent.com/nijasc/ktor-svelte/main/scripts/setup.sh | sh
```
**Windows:**
```powershell
powershell -c "irm https://raw.githubusercontent.com/nijasc/ktor-svelte/main/scripts/setup.ps1 | iex"
```
It asks a few questions. Press Enter to take the defaults. Then it writes the project, installs the frontend, generates the TypeScript client and formats everything.
## 2. Run it
```bash
cd my-app
./gradlew svelteDevAll
```
On Windows, run `gradlew.bat svelteDevAll`. If you chose Postgres, start it first with `docker compose up -d`.
`svelteDevAll` starts Vite, the Kotlin compiler and your app, and opens `http://localhost:8080` once everything answers. `./gradlew dev` is short for the same task. In IntelliJ, open the folder and run the `Dev` configuration instead.
## 3. Look around
The first page of the new app lists what was set up for the answers you gave, each with a link to its docs, and what to do next. Try this:
- Edit `frontend/src/routes/+page.svelte` and save: the page updates without a reload.
- Open `http://localhost:8080/api/hello`: that answer comes from `Application.kt`.
- Click the **API** button in the corner of the page to see every call the app answers.
- Change a route in Kotlin and save: the app restarts, and the typed client in `frontend/src/lib/api` follows.
When something looks off, run `./gradlew svelteDoctor`.
## What the questions mean
| Question | Flag | Default | What you get |
|---|---|---|---|
| Project name, Kotlin package, package manager | `--name`, `--package`, `--package-manager` | `my-app`, `com.example.app`, first one found | |
| TypeScript client | `--generate-ts` | yes | `generateTs` turned on |
| DaisyUI, Tailwind, Lucide | `--daisy`, `--tailwind`, `--lucide` | yes | Configured in `build.gradle.kts` |
| i18n | `--i18n`, `--locales`, `--locale-strategy` | no | Message files and the chosen strategy |
| Sign in | `--auth` | no | Cookie sessions, hashed passwords, routes, and login and account pages |
| Postgres | `--database` | no | Exposed, HikariCP, `compose.yaml` and a small example table |
| Flyway, only with Postgres | `--flyway` | yes | Migrations in `src/main/resources/db/migration` |
| No package folders | `--idea-ext` | yes | Kotlin files directly in `src/main/kotlin`, and IntelliJ knows the package through the `idea-ext` plugin |
| Convention plugin | `--conventions` | no | `build-logic` with shared Kotlin and ktlint setup, for multi-module projects |
| Dockerfile | `--docker` | yes | A multi-stage build that runs the JAR as a non-root user |
| GitHub Actions | `--github-actions` | yes | A CI workflow with Actions pinned to commit SHAs |
| Git repository, only if git is installed | `--git` | yes | `git init` |
| IntelliJ live templates | `--live-templates` | yes | Installs `ksget`, `ksapi` and the other ktor-svelte live templates into every IntelliJ IDEA and WebStorm on the machine |
| Open in IntelliJ, only if it is installed | `--open-idea` | yes, but no with `--yes` | Opens the project when it is ready |
DaisyUI includes Tailwind, so with `--daisy` the Tailwind question is skipped. The languages for i18n are written default first, such as `en,de`, and the strategy is `Cookie` or `UrlPrefix`.
Every project also gets a Gradle version catalog, JSON and typed error responses, ktlint, ESLint and Prettier, a `README.md`, a `.env.example` and a `.gitignore`. With sign in or Postgres, it also gets a `.env` with random secrets, which is not committed. [Project structure](https://nijasc.github.io/ktor-svelte/guide/project-structure) shows where everything lives.
## Build the command
Pick what you want, and copy the command for your system. It skips every question.
To write the command by hand, add `--yes` and any options from the table. `--yes` takes the default for every question you do not answer with a flag. Turn something off with `--no-`, such as `--no-lucide`:
```bash
curl -fsSL https://raw.githubusercontent.com/nijasc/ktor-svelte/main/scripts/setup.sh | sh -s -- --yes --name=shop
```
On Windows, `irm ... | iex` cannot pass options, so run the script as a script block. Put options that contain a comma, such as `--locales=en,de`, in single quotes, or PowerShell splits them:
```powershell
powershell -c "& ([scriptblock]::Create((irm https://raw.githubusercontent.com/nijasc/ktor-svelte/main/scripts/setup.ps1))) --yes --name=shop --i18n '--locales=en,de'"
```
**Pin a release**
The script uses the latest release from Maven Central. Pass a release number, such as `--version=1.0.0`, to create the project with that release instead.
**Read before you run**
Prefer to read scripts before running them? They are in [`scripts/`](https://github.com/nijasc/ktor-svelte/tree/main/scripts). [What runs on your machine](https://nijasc.github.io/ktor-svelte/security#what-runs-on-your-machine) explains what they download.
## Next steps
- Build something real: the [tutorial](https://nijasc.github.io/ktor-svelte/guide/tutorial) takes you from an empty project to a notes app in one JAR.
- See every feature at a glance: [Everything ktor-svelte does](https://nijasc.github.io/ktor-svelte/features).
- Already have an app? [Add to an existing project](https://nijasc.github.io/ktor-svelte/guide/existing-project).
- Tick settings in a form: the [Configurator](https://nijasc.github.io/ktor-svelte/guide/configurator).
Source: https://nijasc.github.io/ktor-svelte/guide/configurator
# Configurator
Tick what your app needs, and copy the two blocks into your project: one for `build.gradle.kts`, one for `install(Svelte)`.
- Only settings that differ from the defaults appear, so the result stays short.
- The panel on the right recommends what most apps should turn on. Click **Apply** to take a recommendation.
## Where to go from here
- Every option is explained in [Gradle settings and tasks](https://nijasc.github.io/ktor-svelte/reference/gradle) and [Ktor settings](https://nijasc.github.io/ktor-svelte/reference/ktor).
- For an existing project, `./gradlew svelteConfig` shows what is set now and scores it the same way. See [Review your configuration](https://nijasc.github.io/ktor-svelte/reference/gradle#review-your-configuration).
- Starting from scratch? The [setup script](https://nijasc.github.io/ktor-svelte/guide/getting-started#build-the-command) writes a whole project for you.
Source: https://nijasc.github.io/ktor-svelte/guide/tutorial
# Tutorial: a notes app
Build a small notes app from an empty folder: a Ktor API, a SvelteKit page that calls it through the generated client, validation on both sides, config from the server, and one JAR at the end. It takes about 20 minutes.
Every step shows the whole file, so you can copy it as it is. The finished, larger version is [`examples/notes`](https://github.com/nijasc/ktor-svelte/tree/main/examples/notes).
**You need** Java 17 or newer and one of Bun, pnpm, npm or Yarn.
**You will build:**
| Step | You learn |
|---|---|
| [1. Create the project](#_1-create-the-project) | The setup script and the dev loop |
| [2. Model the notes](#_2-model-the-notes) | DTOs with validation rules |
| [3. Add the routes](#_3-add-the-routes) | Ktor routes and the generated client |
| [4. Load notes into a page](#_4-load-notes-into-a-page) | `apiWith(event)` in a `load` function |
| [5. Show and change them](#_5-show-and-change-them) | Typed calls from a Svelte page |
| [6. Try the validation](#_6-try-the-validation) | Errors from the browser and from the server |
| [7. Pass config to the frontend](#_7-pass-config-to-the-frontend) | `publicConfig` |
| [8. Run the checks](#_8-run-the-checks) | What keeps the two sides in step |
| [9. Ship one JAR](#_9-ship-one-jar) | `buildFatJar` and Docker |
## 1. Create the project
Run the setup script with the defaults, a project name and a package:
```bash
curl -fsSL https://raw.githubusercontent.com/nijasc/ktor-svelte/main/scripts/setup.sh | sh -s -- --yes --name=notes --package=notes
cd notes
./gradlew svelteDevAll
```
On Windows:
```powershell
powershell -c "& ([scriptblock]::Create((irm https://raw.githubusercontent.com/nijasc/ktor-svelte/main/scripts/setup.ps1))) --yes --name=notes --package=notes"
cd notes
gradlew.bat svelteDevAll
```
`svelteDevAll` starts Vite, the Kotlin compiler and the app, and opens `http://localhost:8080` once everything answers. Leave it running: every step below reloads on save.
With the defaults, Kotlin files sit directly in `src/main/kotlin`, without package folders. This is the `Application.kt` the script wrote:
```kotlin no-check [src/main/kotlin/Application.kt]
package notes
import io.github.nijasc.ktor.svelte.Svelte
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.serialization.Serializable
@Serializable
data class Greeting(
val message: String,
)
fun main() {
val port = env("PORT")?.toInt() ?: 8080
embeddedServer(Netty, port = port, module = Application::module).start(wait = true)
}
fun Application.module() {
install(Svelte) {
generateTs = true
transport {
json()
compression()
}
}
configureErrors()
routing {
get("/api/hello") {
call.respond(Greeting("Hello from Ktor"))
}
}
}
```
`generateTs = true` means the TypeScript client in `frontend/src/lib/api/` is rewritten from your routes each time the app starts. `env` comes from `Env.kt` and reads the environment and `.env`. `configureErrors` comes from `Errors.kt` and turns exceptions into JSON error responses.
## 2. Model the notes
Create `src/main/kotlin/Notes.kt` next to `Application.kt`:
```kotlin [src/main/kotlin/Notes.kt]
package notes
import io.github.nijasc.ktor.svelte.Validated
import io.github.nijasc.ktor.svelte.Validator
import io.ktor.openapi.JsonSchema
import kotlinx.serialization.Serializable
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicInteger
@Serializable
enum class NoteStatus { ACTIVE, ARCHIVED }
@Serializable
data class Note(
val id: Int,
val title: String,
val body: String,
val status: NoteStatus,
)
@Serializable
data class NoteInput(
@JsonSchema.MinLength(1)
@JsonSchema.MaxLength(80)
val title: String,
val body: String = "",
) : Validated {
override fun Validator.rules() {
check(::title, title.isNotBlank()) { "A note needs a title." }
}
}
class NoteStore {
private val ids = AtomicInteger()
private val notes = ConcurrentHashMap()
fun list(): List = notes.values.sortedBy { it.id }
fun create(input: NoteInput): Note = Note(ids.incrementAndGet(), input.title, input.body, NoteStatus.ACTIVE).also { notes[it.id] = it }
fun archive(id: Int): Note? = notes.computeIfPresent(id) { _, note -> note.copy(status = NoteStatus.ARCHIVED) }
fun delete(id: Int): Boolean = notes.remove(id) != null
}
```
The schema annotations and the `Validated` rules do two jobs:
- ktor-svelte checks every received `NoteInput` against them and answers 422 with field errors.
- The generated client gets the same limits for your form.
The store keeps notes in memory, so they are gone after a restart. That is fine for now. [Page through long lists](https://nijasc.github.io/ktor-svelte/recipes/pagination#with-exposed) shows a store on a database.
## 3. Add the routes
Create `src/main/kotlin/NoteRoutes.kt`:
```kotlin [src/main/kotlin/NoteRoutes.kt]
package notes
import io.ktor.http.HttpStatusCode
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.delete
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
fun Route.noteRoutes(store: NoteStore) {
route("/api/notes") {
get {
val notes: List = store.list()
call.respond(notes)
}
post {
val input = call.receive()
call.respond(HttpStatusCode.Created, store.create(input))
}
post("/{id}/archive") {
val note: Note? = store.archive(call.parameters["id"]?.toIntOrNull() ?: -1)
if (note == null) call.respond(HttpStatusCode.NotFound) else call.respond(note)
}
delete("/{id}") {
val deleted = store.delete(call.parameters["id"]?.toIntOrNull() ?: -1)
call.respond(if (deleted) HttpStatusCode.NoContent else HttpStatusCode.NotFound)
}
}
}
```
Register them in `Application.kt`. Create the store above the existing `routing { }` block and add the routes inside it:
```kotlin no-check [src/main/kotlin/Application.kt]
package notes
import io.github.nijasc.ktor.svelte.Svelte
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.response.respond
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.serialization.Serializable
@Serializable
data class Greeting(
val message: String,
)
fun main() {
val port = env("PORT")?.toInt() ?: 8080
embeddedServer(Netty, port = port, module = Application::module).start(wait = true)
}
fun Application.module() {
install(Svelte) {
generateTs = true
transport {
json()
compression()
}
}
configureErrors()
val store = NoteStore()
routing {
get("/api/hello") {
call.respond(Greeting("Hello from Ktor"))
}
noteRoutes(store)
}
}
```
The two lines that changed, on their own:
```kotlin
val store = NoteStore()
routing {
noteRoutes(store)
}
```
Save. The app restarts, and `frontend/src/lib/api/` now contains:
- the types `Note` and `NoteInput`,
- a `Status` enum, because enums are named after the property that uses them, so `status: NoteStatus` becomes `Status`,
- a `notes` service with `list`, `create`, `archive` and `delete`.
Open `http://localhost:8080/_ktor-svelte/routes` to see your routes next to the frontend pages.
**How the names are chosen**
`GET /api/notes` is `list`, `POST` is `create`, `DELETE /{id}` is `delete`, and `POST /{id}/archive` is `archive`. [Calling the API](https://nijasc.github.io/ktor-svelte/features/calling-the-api) has the full rules.
## 4. Load notes into a page
Create `frontend/src/routes/notes/+page.ts`:
```ts [frontend/src/routes/notes/+page.ts]
import { apiWith } from '#api';
import type { PageLoad } from './$types';
export const prerender = false;
export const ssr = false;
export const load: PageLoad = async (event) => ({
notes: await apiWith(event).notes.list()
});
```
- `prerender = false` and `ssr = false`: the page depends on data from your API, so it is rendered in the browser and not at build time.
- `apiWith(event)` uses SvelteKit's `fetch` inside `load`. See [In load functions](https://nijasc.github.io/ktor-svelte/features/calling-the-api#in-load-functions).
## 5. Show and change them
Create `frontend/src/routes/notes/+page.svelte`:
```svelte [frontend/src/routes/notes/+page.svelte]
Notes
{#each notes as note (note.id)}
{note.title}
{note.body}
{:else}
No notes yet.
{/each}
```
Open `http://localhost:8080/notes`. Add a note, archive it, delete it.
Every call is typed. Try it: rename `body` in `NoteInput`, save, and `svelte-check` points at each line that needs to change. Rename it back before you go on.
## 6. Try the validation
The form has two layers of checks, and you can see both:
1. **Submit an empty title.** `NoteInput.validate` shows "Must be at least 1 character." without sending a request, because the generated client knows the `MinLength` annotation.
2. **Type only spaces.** That passes the browser check, but the `isNotBlank` rule runs on the server, which answers 422, and `isValidationError` shows "A note needs a title." under the field.
Rules in `Validated.rules()` only run on the server. Annotations run on both sides. See [Validation](https://nijasc.github.io/ktor-svelte/features/validation) for every annotation and for [form state](https://nijasc.github.io/ktor-svelte/features/validation#form-state), which saves you the error variables.
## 7. Pass config to the frontend
Values that differ per environment, such as the app name, come from Ktor at startup. Add a class to `Notes.kt`:
```kotlin
@Serializable
data class AppConfig(
val appName: String,
)
```
Pass it in `install(Svelte)`. `env` comes with the generated project and also reads `.env`:
```kotlin
publicConfig(AppConfig(appName = env("APP_NAME") ?: "Notes"))
```
In the whole `install(Svelte)` block, that is:
```kotlin no-check [src/main/kotlin/Application.kt]
install(Svelte) {
generateTs = true
publicConfig(AppConfig(appName = env("APP_NAME") ?: "Notes"))
transport {
json()
compression()
}
}
```
Load it next to the notes in `frontend/src/routes/notes/+page.ts`:
```ts [frontend/src/routes/notes/+page.ts]
import { apiWith, loadPublicConfig } from '#api';
import type { PageLoad } from './$types';
export const prerender = false;
export const ssr = false;
export const load: PageLoad = async (event) => ({
notes: await apiWith(event).notes.list(),
config: await loadPublicConfig()
});
```
Use `{data.config.appName}` as the heading of the page:
```svelte
{data.config.appName}
```
- In production the config is inlined into every page, so `loadPublicConfig()` reads it without a request.
- In development Vite serves the pages, so it is fetched once.
**Never put secrets in it**
Anyone can read the public config. Keep keys and passwords on the server. See [Runtime config](https://nijasc.github.io/ktor-svelte/features/runtime-config).
## 8. Run the checks
Stop `svelteDevAll`, then format both sides and run the checks:
```bash
./gradlew format
./gradlew check
```
`check` starts your app once, generates the TypeScript in memory and fails if the committed client differs from it. So a changed DTO or route can never drift away from the frontend unnoticed, also in CI. The project came with a GitHub Actions workflow that runs this for you.
## 9. Ship one JAR
Build the JAR and run it:
```bash
./gradlew buildFatJar
APP_NAME="My notes" java -jar build/libs/notes-all.jar
```
On Windows:
```powershell
$env:APP_NAME = "My notes"; java -jar build\libs\notes-all.jar
```
The JAR contains the API, the built frontend and its manifest. Open `http://localhost:8080/notes`: same app, now with compressed, cached files and a strict Content-Security-Policy.
The project also came with a `Dockerfile` that builds the same JAR and runs it as a non-root user:
```bash
docker build -t notes .
docker run -p 8080:8080 -e APP_NAME="My notes" notes
```
Before you deploy for real, `./gradlew svelteSmokeTest` starts the packaged app in production mode and checks that every page and API route answers. See [Deployment](https://nijasc.github.io/ktor-svelte/guide/deployment) for Docker, reverse proxies and a checklist.
## Where to go next
- Tags, search, paging and uploads: [examples/notes](https://github.com/nijasc/ktor-svelte/tree/main/examples/notes) and the [recipes](https://nijasc.github.io/ktor-svelte/recipes)
- Less route code: [resource routes](https://nijasc.github.io/ktor-svelte/features/typescript#resource-routes) register list, get, create, update and delete in one block
- Sign-in with a session cookie: [Sessions](https://nijasc.github.io/ktor-svelte/recipes/sessions)
- Everything the client can do: [Calling the API](https://nijasc.github.io/ktor-svelte/features/calling-the-api)
- Every feature at a glance: [Everything ktor-svelte does](https://nijasc.github.io/ktor-svelte/features)
Source: https://nijasc.github.io/ktor-svelte/guide/existing-project
# Add to an existing project
Already have a Ktor app, a SvelteKit app, or both? Add ktor-svelte in a few steps. Starting from nothing is quicker with [Getting started](https://nijasc.github.io/ktor-svelte/guide/getting-started).
**You need** a Kotlin JVM project that uses the `application` plugin, Java 17 or newer, and one of Bun, pnpm, npm or Yarn.
## 1. Add the Gradle plugin
In `build.gradle.kts`:
```kotlin
plugins {
id("io.github.nijasc.ktor-svelte") version "1.4.0"
}
```
The Gradle plugin adds the runtime library, `ktor-svelte-server`, for you.
## 2. Add the frontend
### A new frontend
This writes a working SvelteKit 3 project to `frontend/`, with a `.gitignore` and an `.editorconfig` that matches the Kotlin side, and installs it with the first package manager on your `PATH`:
```bash
./gradlew svelteInit
```
Pass `--package-manager=bun`, or `pnpm`, `npm` or `yarn`, to pick one.
### A frontend you already have
Move it to `frontend/`, or point `frontendDir` in `svelte { }` at it. It needs `adapter-static`, and since SvelteKit 3 has no `svelte.config.js`, the configuration goes in `frontend/vite.config.ts`:
```ts
import { sveltekit } from '@sveltejs/kit/vite';
import adapter from '@sveltejs/adapter-static';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit({ adapter: adapter({ fallback: '200.html' }) })],
server: { hmr: { clientPort: 5173, protocol: 'ws' } }
});
```
- `fallback: '200.html'` gives pages that are not prerendered a page to start from.
- `server.hmr` makes Vite's client connect straight to Vite, also when the page comes through Ktor's port. See [Dev workflow](https://nijasc.github.io/ktor-svelte/guide/dev-workflow).
Run `./gradlew svelteDoctor` to check the rest: the adapter, its output folder, the `#api` import, `tsconfig`, the Kit and Node versions, and more.
## 3. Install the Ktor plugin
```kotlin
import io.github.nijasc.ktor.svelte.Svelte
fun Application.module() {
install(Svelte)
routing {
get("/api/hello") { call.respondText("hi") }
}
}
```
That is all it needs. Turn on the [TypeScript client](https://nijasc.github.io/ktor-svelte/features/typescript) with `generateTs = true` and the [JSON transport](https://nijasc.github.io/ktor-svelte/features/transport) with `transport { json() }` inside `install(Svelte) { }` when you want them. Every other setting is in [Ktor settings](https://nijasc.github.io/ktor-svelte/reference/ktor).
**Already installing ContentNegotiation, RequestBodyLimit or RateLimit?**
ktor-svelte tells you at startup when one of its defaults clashes with a plugin you install yourself. [Troubleshooting](https://nijasc.github.io/ktor-svelte/reference/troubleshooting#startup) lists each message and the fix.
## 4. Run it
The frontend is built first and served from the same port as your API:
```bash
./gradlew run
```
For development with hot reload, run `./gradlew svelteDevAll` instead. See [Dev workflow](https://nijasc.github.io/ktor-svelte/guide/dev-workflow).
## 5. Package one JAR
For one runnable JAR, add [Shadow](https://gradleup.com/shadow/) or Ktor's Gradle plugin and run `shadowJar` or `buildFatJar`. The frontend comes along automatically. See [Deployment](https://nijasc.github.io/ktor-svelte/guide/deployment).
## Optional extras
### IntelliJ run configurations
This writes run configurations to `.run/`:
```bash
./gradlew svelteGenerateRunConfigurations
```
### Only the library
The Gradle plugin adds the runtime for you. If you only want the library, without the Gradle plugin, add it directly:
```kotlin
implementation("io.github.nijasc:ktor-svelte-server:1.4.0")
```
Without the Gradle plugin, building the frontend and copying it into the JAR is up to you.
### Versions that are tested together
To keep Kotlin, Ktor and ktor-svelte on versions that are tested together, import the published version catalog in `settings.gradle.kts`:
```kotlin
dependencyResolutionManagement {
versionCatalogs {
create("ktorSvelte") {
from("io.github.nijasc:ktor-svelte-catalog:1.4.0")
}
}
}
```
Then use its aliases in `build.gradle.kts`, and upgrade everything by changing that one version:
```kotlin
plugins {
alias(ktorSvelte.plugins.kotlin.jvm)
alias(ktorSvelte.plugins.kotlin.serialization)
alias(ktorSvelte.plugins.ktor)
alias(ktorSvelte.plugins.ktor.svelte)
}
dependencies {
implementation(ktorSvelte.ktor.server.netty)
}
```
It has the `kotlin`, `ktor`, `serialization` and `ktor-svelte` versions, the plugins above, `ktor-svelte-server`, `ktor-bom`, the common Ktor server modules and `kotlinx-serialization-json`.
## Next steps
- Check that everything fits: `./gradlew svelteDoctor`, and `./gradlew svelteConfig` for an overview of your settings
- See what goes where: [Project structure](https://nijasc.github.io/ktor-svelte/guide/project-structure)
- Find a feature: [Everything ktor-svelte does](https://nijasc.github.io/ktor-svelte/features)
Source: https://nijasc.github.io/ktor-svelte/guide/project-structure
# Project structure
What goes where in a ktor-svelte project, and which files are yours to edit.
A project created by the [setup script](https://nijasc.github.io/ktor-svelte/guide/getting-started) looks like the tree below. Projects that add ktor-svelte to an existing app have the same core: a Gradle build with the plugin, a Ktor app with `install(Svelte)`, and a SvelteKit app in `frontend/`.
## The tree
```text
my-app/
build.gradle.kts plugins, svelte { } settings, dependencies
settings.gradle.kts
gradle.properties
gradle/libs.versions.toml version catalog
gradlew, gradlew.bat Gradle wrapper
src/main/kotlin/
Application.kt embeddedServer, install(Svelte), routes
Env.kt env() and requireEnv(), reading the environment and .env
Errors.kt typed error responses
Auth.kt if you chose sign in
Database.kt if you chose Postgres
src/main/resources/
logback.xml
db/migration/ if you chose Flyway
frontend/
package.json
vite.config.ts generated by ktor-svelte
vite.user.ts your own Vite settings, if you need any
messages/ i18n message files, if i18n is on
src/
app.html
routes/ your pages
lib/api/ generated TypeScript client
lib/ktor-svelte/ generated helpers for themes, icons, i18n and more
.run/ IntelliJ run configurations
.env.example every variable the app reads
.env local secrets, if you chose sign in or Postgres; not committed
compose.yaml if you chose Postgres
Dockerfile if you chose Docker
.github/workflows/ci.yml if you chose GitHub Actions
build-logic/ if you chose the convention plugin
README.md
```
With `--no-idea-ext`, the Kotlin files sit in package folders, such as `src/main/kotlin/com/example/app/`, instead of directly in `src/main/kotlin`.
## Files you own and files ktor-svelte owns
ktor-svelte writes some files for you and keeps them up to date. Each of them starts with a "Generated by ktor-svelte" header, and the line after it links to the docs page that explains the file, so a teammate who opens it knows where to look. The files in `src/lib/api` have no header of their own; their `.gitattributes` carries it instead.
**Do not edit generated files**
The next sync or start overwrites your changes.
| File | Written by | Changes when |
|---|---|---|
| `frontend/src/lib/api/*` | the app in development, or `svelteGenerateTs` | a route or DTO changes |
| `frontend/vite.config.ts` | `svelteSync` | library settings change |
| `frontend/src/lib/ktor-svelte/*` | `svelteSync` | themes, icons or locales change |
| `frontend/src/hooks*.ts` | `svelteSync` | i18n or theme settings change |
| Kotlin `AppTheme` and `Messages` classes | the Gradle build, in `build/generated`, never committed | themes or messages change |
Everything else is yours. ktor-svelte never overwrites a file without the header. If it needs to own a file you already have, such as your own `vite.config.ts`, the build stops and tells you what to move. Put custom Vite settings in `vite.user.ts`.
### Commit the generated files
Commit the generated frontend files. That way:
- a frontend build never needs the JVM app to run first,
- `svelteVerifyTs` and `svelteVerifySync` in `check` fail when they are out of date, so a changed DTO cannot drift away from the frontend unnoticed.
Each generated folder also gets a `.gitattributes` that marks its files as generated. [Generated files without merge conflicts](https://nijasc.github.io/ktor-svelte/reference/gradle#generated-files-without-merge-conflicts) shows how to keep two branches from fighting over them.
## The `#api` import
`svelteInit` and `svelteSync` add an import alias to `frontend/package.json`, so pages import the generated client the same way wherever they are:
```ts
import { api, isApiError, type Note } from '#api';
```
Libraries add their own short imports next to it, such as `#routes` for [typed routes](https://nijasc.github.io/ktor-svelte/features/routes) and `#components/...` for the [ready-made components](https://nijasc.github.io/ktor-svelte/features/components).
## What ends up in the JAR
`svelteBundle` copies the static build into `ktor-svelte/public/` in your resources and writes `ktor-svelte/manifest.json`. Hidden files such as `.env` and source maps are left out. The [How it works](https://nijasc.github.io/ktor-svelte/reference/how-it-works) page explains how requests are answered from the manifest.
Source: https://nijasc.github.io/ktor-svelte/guide/multiple-frontends
# Multiple frontends
One app can serve more than one SvelteKit project, such as a public site at `/` and an admin area under `/admin`. Each frontend has its own build, its own pages and its own fallback page, and they all share the one Ktor API.
It is opt-in: an app that declares no second frontend works exactly as before.
## How it works
- **The main frontend** is the one you already have. It keeps every path that no other frontend claims.
- **Each other frontend** gets a path prefix, such as `/admin`. A request goes to the frontend with the longest prefix that covers it, so `/admin/reports` can be a frontend of its own inside `/admin`. A prefix covers whole path segments only: `/admin` covers `/admin` and `/admin/users`, but not `/administrator`.
- **The API stays global.** `apiPrefixes` are checked first, for every frontend, and a frontend may not sit inside an API prefix.
- **Each frontend has its own build and manifest.** In the JAR they live under `ktor-svelte/frontends//`, next to the main frontend's `ktor-svelte/`. The name is the prefix without its slashes, such as `admin` for `/admin` and `admin-reports` for `/admin/reports`.
- **Each frontend answers like the main one**: its pages, its `_app` files with the same cache headers, compression and Content-Security-Policy, its own `spaFallback` and `notFoundPage`, and redirects that stay inside its prefix.
## On the server
```kotlin
install(Svelte) {
frontend("/admin") {
spaFallback = "200.html"
notFoundPage = "404.html"
}
}
```
| Setting | Default | What it does |
|---|---|---|
| `source` | `SvelteSource.Classpath` | Where the build is: from the classpath under `ktor-svelte/frontends//`, or `SvelteSource.Directory(path)` |
| `spaFallback` | `"200.html"` | The page for paths that have no page of their own, inside this frontend |
| `notFoundPage` | `"404.html"` | The page for missing paths, when there is no fallback |
| `paramRoutes(...)` | none | Like the main `paramRoutes`, with paths relative to the prefix |
| `devUrl` | set by `svelteDevAll` | The Vite of this frontend in development. Without one, development serves its build |
| `generateTsOutput` | `src/lib/api` in the frontend's folder | Where its copy of the typed client goes, when `generateTs` is on |
Outside development, a frontend without a build stops the start, like the main frontend does. In development it is a warning.
## In Gradle
Declare the frontend in `build.gradle.kts`, under the same name the server derives from its prefix:
```kotlin
svelte {
frontend("admin") {
frontendDir = layout.projectDirectory.dir("admin")
}
}
```
| Setting | Default | What it does |
|---|---|---|
| `frontendDir` | the folder named like the frontend, such as `admin` | Directory of its SvelteKit project |
| `outputDir` | `outputDir` of the main frontend, `"build"` | Adapter output, a folder inside its `frontendDir` |
| `buildScript` | `buildScript` of the main frontend, `"build"` | `package.json` script that builds it |
| `basePath` | `"/"` and the name, such as `"/admin"` | The path prefix it is built for. Set it for a nested prefix, such as `"/admin/reports"` for the frontend `admin-reports` |
| `devPort` | the next port after `dev.port`, such as `5174` | Port of its Vite |
Each frontend gets its own tasks, named after it: `svelteInstallAdmin`, `svelteBuildAdmin` and `svelteBundleAdmin`. They run with the main frontend's tasks when the JAR is built, and `svelteBundleAdmin` puts the build under `ktor-svelte/frontends/admin/`, where `install(Svelte) { frontend("/admin") }` reads it. The settings that are not per frontend, such as `packageManager`, `bunVersion`, `precompress` and `includeSourceMaps`, apply to every frontend.
When no page of the build loads its files from `/admin/_app/`, `svelteBundleAdmin` warns: the base path is missing from the frontend's Vite config.
## The typed client
With `generateTs = true`, every frontend gets the same generated client as the main one, in its own `src/lib/api`, so the admin pages call the API with the same types. The frontend's folder comes from Gradle (`svelteDevAll`, `run` and `svelteGenerateTs` pass it to the app); without Gradle it is the folder named like the frontend, or set `generateTsOutput`.
## In development
`svelteDevAll` starts one Vite per frontend, each on its own `devPort`, and tells the app where they are, so `/admin` shows the admin project with hot reload while `/` shows the main one. Through the app's port, the dev panel and the browser logs work on every frontend.
Vite serves a project with a base path under that path, so the app forwards `/admin/...` to the admin Vite as it is. To run one frontend's Vite on its own, use `svelteDevAdmin`, and give the app its address with `devUrl`.
## In the frontend project
A second frontend is a SvelteKit project with `adapter-static` like the main one, built for its prefix. Set the base path in its Vite config, so its links and its `_app` files carry the prefix:
```ts
import { sveltekit } from '@sveltejs/kit/vite';
import adapter from '@sveltejs/adapter-static';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit({ adapter: adapter({ fallback: '200.html', precompress: true }), paths: { base: '/admin' } })],
server: { hmr: { clientPort: 5174, protocol: 'ws' } }
});
```
Links inside it go through `resolve()` from `$app/paths`, as SvelteKit asks for any app with a base path. The `hmr` line points hot reload at the frontend's own Vite, on its `devPort`.
- SvelteKit writes asset paths relative to the page, and for the start page of a base path it counts on a slash at the end. So the app answers `/admin` with a redirect to `/admin/`, and the start page loads its files from `/admin/_app/`.
- A link from one frontend into another, such as from the public site to `/admin`, needs `data-sveltekit-reload`, so the browser loads the other app instead of SvelteKit looking for a route of its own.
- A prerendered page with such a link makes the prerender crawler visit `/admin` in the wrong app. Let it pass with `prerender: { handleHttpError }` in the main frontend's `sveltekit()` options, as the example does.
## Example
[`examples/two-frontends`](https://github.com/nijasc/ktor-svelte/tree/main/examples/two-frontends) is a public site and an admin area under `/admin`, each with a page that calls the API through its own generated client. Its browser tests open both in the packaged JAR and check where their files come from, the navigation inside each frontend, the links between them and the fallback pages, and a development mode test runs `svelteDevAll` with two Vite servers.
## Limits
These parts of ktor-svelte know only the main frontend for now:
- The sitemap and `robots.txt`, the default favicon and the language redirect of i18n.
- The startup warning about Ktor routes that hide a page, the route table and the route map of the dev panel.
- The build fingerprint in `X-Ktor-Svelte-Build` and in the status endpoint.
- `svelteVerifyTs` checks the main frontend's client only.
- The typed page routes (`FrontendRoutes`) and the generated Kotlin of `libraries { }` come from the main frontend.
- In Gradle, `libraries { }` with `svelteSync`, the `svelteVerify...` checks, `svelteVerifyLeaks`, `svelteCheck` and the other frontend tools work on the main frontend. Another frontend is installed, built and packaged; add what it needs to its own `package.json`.
Source: https://nijasc.github.io/ktor-svelte/guide/comparison
# Compared with other setups
ktor-svelte is one way to put a Ktor API and a SvelteKit frontend together. This page compares it with the common alternatives, so you can tell whether it fits before you start.
## The short answer
- **Choose ktor-svelte** when the backend is on the JVM, you want one artifact to deploy, and you want the frontend to fail at compile time when the API changes.
- **Choose SvelteKit with `adapter-node`** when you need server-side rendering on every request.
- **Choose a CDN plus a separate API** when the frontend has its own team and release schedule, or a very high share of the traffic.
- **Serve the build by hand** only for a small app with a few pages.
## At a glance
| | ktor-svelte | SvelteKit `adapter-node` in front of Ktor | Static frontend on a CDN, Ktor API elsewhere | Ktor `staticResources` by hand |
|---|---|---|---|---|
| Processes in production | 1 JVM | Node and JVM | JVM, plus the CDN | 1 JVM |
| Origins | One | One, through the Node server | Two, so CORS | One |
| Server-side rendering per request | No, prerendering at build time | Yes | No | No |
| Typed client for your Ktor routes | Generated | Write or generate it yourself | Write or generate it yourself | Write or generate it yourself |
| SPA fallback, trailing slashes, stale chunk 404s | Built in | Built in | CDN rules | Write them yourself |
| Caching headers, ETags, precompressed files | Built in | Built in for assets | CDN | Partly, configure yourself |
| Dev loop | One command, hot reload on Ktor's port | Two servers, proxy config | Two servers, CORS in dev | Rebuild the frontend or run two servers |
| Deploy | One JAR | Two artifacts | Two artifacts | One JAR |
## SvelteKit with `adapter-node` in front of Ktor
SvelteKit runs as its own Node server, renders pages per request, and calls Ktor from `+page.server.ts` or forwards `/api` to it.
**Pick this when** you need per-request server-side rendering: pages with personal data that search engines must see, or first paint from data that changes on every request. You also get `+server.ts` endpoints and form actions.
**The cost** is two runtimes to deploy, monitor and scale, auth that has to work in both, and a hop between them.
**With ktor-svelte**, prerendered pages cover content known at build time, and pages that need API data render in the browser. The [FAQ](https://nijasc.github.io/ktor-svelte/reference/faq) explains this choice in more detail.
## A static frontend on a CDN with a separate Ktor API
The frontend is built with `adapter-static` and uploaded to a CDN or object storage, and the browser calls Ktor on another domain.
**Pick this when** the frontend has a very high share of traffic, or a team that deploys it on its own schedule. The CDN serves files from close to the user.
**The cost** is two deployments that must stay compatible, CORS and its preflight requests, and cookies that need `SameSite=None` or a shared parent domain.
**With ktor-svelte**, there is one origin, so cookies and the origin check work without extra configuration. You can still put a CDN in front of the single app: hashed files under `/_app/immutable/` are marked cacheable forever.
## Ktor serving the build with `staticResources`
You copy the SvelteKit build into your resources yourself and serve it with Ktor's static content support.
**This works** for a small app with only a few pages.
**Everything ktor-svelte adds is left to you:**
- wiring the frontend build into Gradle,
- the SPA fallback that does not swallow API 404s,
- redirects for trailing slashes,
- real 404s for missing chunks after a deploy,
- precompressed files,
- CSP hashes for SvelteKit's inline scripts,
- the dev proxy,
- and the TypeScript client.
## Other full-stack frameworks
- **Spring Boot with a frontend build plugin** follows the same idea on Spring. ktor-svelte is the Ktor and SvelteKit version, with the generated client and dev proxy included.
- **Kotlin frontend frameworks**, such as Compose for Web or Kobweb, share one language across the stack. ktor-svelte keeps the frontend in TypeScript and Svelte, and shares types through the generated client instead.
- **JavaScript full-stack frameworks**, such as SvelteKit on its own, Next.js or Nuxt, keep everything in one JavaScript runtime. Choose ktor-svelte when the backend is, or should be, on the JVM.
## When ktor-svelte is not the right fit
- You need server-side rendering on every request.
- The frontend and the backend are deployed by different teams on different schedules.
- The app mounts under a sub-path, which ktor-svelte does not support yet.
- You want SvelteKit's `+page.server.ts`, `+server.ts` or form actions. In ktor-svelte, Ktor routes take their place.
Still deciding? The [examples](https://nijasc.github.io/ktor-svelte/examples) run with one command, and [Getting started](https://nijasc.github.io/ktor-svelte/guide/getting-started) creates a project in a couple of minutes.
Source: https://nijasc.github.io/ktor-svelte/examples
# Examples
Three example apps live in the repository, from the smallest possible app to a full team board with sign in. They are separate Gradle builds that use ktor-svelte the way your project does, and they double as the end-to-end tests, so they always work with the current code.
| Example | Size | Best for |
|---|---|---|
| [basic](#basic) | One route, three pages | Seeing the minimum that works |
| [notes](#notes) | A notes app | Each feature on its own, easy to find |
| [showcase](#showcase) | A team board with users | Features working together in a real app |
| [two-frontends](#two-frontends) | A public site and an admin area | [Multiple frontends](https://nijasc.github.io/ktor-svelte/guide/multiple-frontends) in one app |
## Run them
Clone the repository, then start an example with everything in one command:
```bash
git clone https://github.com/nijasc/ktor-svelte.git
cd ktor-svelte
./gradlew -p examples/notes svelteDevAll
```
Open `http://localhost:8080`. In IntelliJ, open the repository and run the `Notes: Dev`, `Showcase: Dev` or `Basic: Dev` run configuration instead. You need Java 17 or newer and [Bun](https://bun.sh).
To build and run the production JAR:
```bash
./gradlew -p examples/notes buildFatJar
```
```bash
java -jar examples/notes/build/libs/notes-all.jar
```
The showcase builds the same way with `buildFatJar`. The basic example uses Shadow instead, so its task is `shadowJar`.
## basic
[`examples/basic`](https://github.com/nijasc/ktor-svelte/tree/main/examples/basic) is the smallest possible app: `install(Svelte)` with no settings, one API route and three pages.
| Look at | To see |
|---|---|
| `src/main/kotlin/Application.kt` | `install(Svelte)` with no settings, and one API route |
| `frontend/src/routes/+page.svelte`, `about/` | Prerendered pages |
| `frontend/src/routes/app/` | A page that renders in the browser and calls the API |
| `frontend/vite.config.ts` | The `adapter-static` setup SvelteKit needs |
Start here when you want to see what ktor-svelte does before any of its options.
## notes
[`examples/notes`](https://github.com/nijasc/ktor-svelte/tree/main/examples/notes) is a small notes app that uses almost every feature, each in a place that is easy to find. The [tutorial](https://nijasc.github.io/ktor-svelte/guide/tutorial) builds a smaller version of it step by step.
| Look at | To see |
|---|---|
| `src/main/kotlin/notes/Application.kt` | `generateTs`, `transport { json(); xml(); compression() }`, `publicConfig` and `apiDocs` |
| `src/main/kotlin/notes/Model.kt` | DTOs with `@JsonSchema` bounds and `Validated` rules, a query class, a sealed `Activity` and `Page` |
| `src/main/kotlin/notes/Routes.kt` | CRUD routes with `resource`, typed 404 errors, a paged feed with `getPage` and multipart attachments |
| `build.gradle.kts` | Tailwind, DaisyUI with a custom theme, Lucide, typed routes, images, toasts and i18n, all in `svelte { libraries { } }` |
| `frontend/src/lib/api/` | The generated client, committed |
| `frontend/src/routes/notes/+page.svelte` | Forms with `use:field`, client and server validation, search and tag filters |
| `frontend/src/routes/notes/[id]/` | A dynamic route with `apiWith(event)` in `load` and typed errors |
| `frontend/src/routes/+layout.svelte` | DaisyUI themes, Lucide icons and i18n with a language switcher |
| `src/e2eTest/kotlin/NotesAppTest.kt` | How the production JAR is tested end to end |
### Things to try
While `svelteDevAll` runs:
- Change a Svelte file: the page updates without a reload.
- Add a property to `Note` in `Model.kt`: the app restarts, and `frontend/src/lib/api/types.ts` gains the property a moment later.
- Open `http://localhost:8080/api/docs` for Swagger UI.
- Submit an empty title: the error comes from the generated `validate()` before any request is sent.
- Click the **API** button in the corner of a page to see every call, with its status and time.
## showcase
[`examples/showcase`](https://github.com/nijasc/ktor-svelte/tree/main/examples/showcase) is a team board that people sign in to. Where notes shows each feature on its own, the showcase shows them working together the way a real app needs them: pages behind a login, an admin area, a database and uploads.

```bash
./gradlew -p examples/showcase svelteDevAll
```
### Signing in
The first start creates two people, `ada@example.com` as admin and `grace@example.com` as member. Set their passwords with `SHOWCASE_ADMIN_PASSWORD` and `SHOWCASE_MEMBER_PASSWORD`, at least 10 characters each. Without them, the app generates passwords and writes them to its log once.
The data lives in `examples/showcase/build/showcase-data`, so `./gradlew -p examples/showcase clean` starts over.
### Where to look
| Look at | To see |
|---|---|
| `src/main/kotlin/showcase/Application.kt` | `routing = SvelteRouting.Manual` with public pages, everything else behind `authenticate`, a named rate limit and a health check that asks the database |
| `src/main/kotlin/showcase/Application.kt` | Environment variables declared once with `environment`, and `startupStep` for the slow parts of startup |
| `src/main/kotlin/showcase/Application.kt` | `currentUser`, `loginPage`, `permissions`, `preferences` and page `guards`, declared once for both sides |
| `src/main/kotlin/showcase/Application.kt` | `constants`, `errorCodes`, `idempotency()`, `frontendErrors()`, `webVitals` and a typed cookie |
| `src/main/kotlin/showcase/Auth.kt` | A signed session cookie, sign in, registration, and an admin area guarded on the server |
| `src/main/kotlin/showcase/Database.kt`, `src/main/resources/db/migration/` | Exposed on an embedded H2 database, with Flyway migrations |
| `src/main/kotlin/showcase/TaskRoutes.kt` | Paged and filtered lists, typed errors in the language of the person, multipart uploads with a size and type check, and downloads that browsers never run as a page |
| `src/main/kotlin/showcase/Model.kt` | `@JsonSchema` bounds, `Validated` rules and a sealed `Activity` that becomes a TypeScript union |
| `build.gradle.kts` | Every frontend library at once: themes with a custom one, fonts, charts, an installable app, components, toasts with a reload prompt and i18n |
| `frontend/src/routes/+layout.svelte` | The generated `currentUser` store that the header reads |
| `frontend/src/routes/(app)/+layout.ts` | A layout group for the pages that need a session |
| `frontend/src/routes/(app)/board/+page.svelte` | Search as you type with `latest`, filters, "load more" with a cursor, and `prefetchOnHover` |
| `frontend/src/routes/(app)/tasks/[id]/+page.svelte` | Uploads with a progress bar, comments, `Activity.match` and a confirm dialog |
| `frontend/src/lib/components/TaskForm.svelte` | One form for creating and editing, with `use:field` and errors from the browser and the server |
| `frontend/messages/` | English and German texts that the pages and the API errors share |
| `frontend/src/emails/Welcome.svelte` | A welcome email in English and German with a shared layout, rendered on registration and shown to admins at `/api/admin/emails/welcome` |
| `src/e2eTest/kotlin/ShowcaseAppTest.kt` | Sessions, roles, uploads, paging and rate limits tested against the production JAR |
| `src/browserTest/kotlin/ShowcaseBrowserTest.kt` | The same JAR driven by Playwright in Chromium, Firefox and WebKit, with accessibility checks |
| `src/devBrowserTest/kotlin/DevModeBrowserTest.kt` | `svelteDevAll` with a browser: hot reload, a restart after a Kotlin change, and browser errors in the dev log |
### Environment variables
| Variable | What it does |
|---|---|
| `PORT` | The port the server listens on, 8080 unless you set it |
| `SESSION_SIGN_KEY` | 64 hex characters that sign the session cookie, so sessions survive a restart |
| `SHOWCASE_DATA` | Where the database and the uploaded files go |
| `SHOWCASE_REGISTRATION` | `closed` stops new people from creating an account |
| `SHOWCASE_LOGIN_ATTEMPTS` | Sign-in attempts allowed per minute, 10 unless you set it |
| `SHOWCASE_SESSION_SECONDS` | How long someone stays signed in, a week unless you set it |
| `SHOWCASE_SITE_URL` | The public address of the site, for the sitemap |
| `SHOWCASE_INSECURE_COOKIES` | `true` to test the JAR over plain HTTP in browsers that do not treat `localhost` as secure |
| `APP_NAME` | The name shown in the header |
The pictures on the [start page](https://nijasc.github.io/ktor-svelte/) come from `./gradlew -p examples/showcase screenshots`, which starts the showcase JAR in a headless Chromium.
## Your own examples
The [recipes](https://nijasc.github.io/ktor-svelte/recipes/) show complete solutions for sessions, uploads, live updates, paging and an admin area that you can copy into your app. [Everything ktor-svelte does](https://nijasc.github.io/ktor-svelte/features/) links every feature to its page.
## two-frontends
Two SvelteKit projects in one app: the public site in `frontend/` and an admin area in `admin/`, served under `/admin`.
| Look at | To see |
|---|---|
| `src/main/kotlin/twofrontends/Application.kt` | `frontend("/admin")` and `generateTs` with one API route |
| `build.gradle.kts` | `svelte { frontend("admin") { } }`, and ports you can change with `-PvitePort`, `-PadminVitePort` and `-PdebugPort` |
| `admin/vite.config.ts` | `paths: { base: '/admin' }` and the admin's own hot reload port |
| `frontend/src/lib/api/`, `admin/src/lib/api/` | The same generated client in both frontends |
| `src/browserTest/` | Both frontends in a browser, from the packaged JAR |
| `src/devBrowserTest/` | `svelteDevAll` with one Vite per frontend |
Source: https://nijasc.github.io/ktor-svelte/features/
# Everything ktor-svelte does
Every feature in one place, grouped by what you are doing. Each row links to the page that explains it, with snippets and every option.
**Where it lives** tells you where you turn a feature on or use it:
| Label | Means |
|---|---|
| | `install(Svelte) { }` and helpers in your Kotlin routes, from `ktor-svelte-server` |
| | `svelte { }` in `build.gradle.kts`, or a Gradle task |
| | Code that ktor-svelte writes into your frontend, imported as `#api`, `#routes` or `#components/...` |
| | `ktor-svelte-test`, for Kotlin tests that drive a browser |
A few rows say Recipe, Script, Docs, Release or This site instead: those are guides, the setup script, or things that happen outside your app.
New here? Start with [Getting started](https://nijasc.github.io/ktor-svelte/guide/getting-started) or the [tutorial](https://nijasc.github.io/ktor-svelte/guide/tutorial). Looking for a whole solution, such as sign in or uploads? See the [recipes](https://nijasc.github.io/ktor-svelte/recipes).
[[toc]]
## Kotlin to TypeScript
Your Ktor routes and classes become a typed client, so the frontend breaks at compile time, not in production.
### The generated client
| Feature | What it does | Where it lives |
|---|---|---|
| [Generated TypeScript](https://nijasc.github.io/ktor-svelte/features/typescript) | Types, services, `validate()`, `empty()` and enum objects for every route, written to `frontend/src/lib/api` with no npm dependencies | Ktor plugin, Generated client |
| [Exact types](https://nijasc.github.io/ktor-svelte/features/typescript#getting-exact-types) | Ktor's compiler plugin reads `receive` and `respond`, or you describe a route by hand | Gradle |
| [Documentation in the editor](https://nijasc.github.io/ktor-svelte/features/typescript#documentation-in-the-editor) | `describe { }` and `@JsonSchema.Description` become JSDoc, deprecations become `@deprecated`, and each function names its Kotlin file | Generated client |
| [Dates](https://nijasc.github.io/ktor-svelte/features/typescript) | `LocalDate`, `LocalTime`, `Instant` and `LocalDateTime` become `IsoDate`, `IsoTime` and `IsoDateTime`, with safe converters | Generated client |
| [Shared constants](https://nijasc.github.io/ktor-svelte/features/typescript#shared-constants) | A Kotlin object with limits and lists, written to `constants.ts` | Ktor plugin, Generated client |
| [IDs that cannot be mixed up](https://nijasc.github.io/ktor-svelte/features/typescript#ids-that-cannot-be-mixed-up) | A Kotlin value class becomes its own TypeScript type | Generated client |
| [Money and durations](https://nijasc.github.io/ktor-svelte/features/typescript#money-and-durations) | Exact `Decimal` values and `Duration` as text, with helpers | Ktor plugin, Generated client |
| [Sealed classes](https://nijasc.github.io/ktor-svelte/features/typescript#sealed-classes) | A union with a `type` field and an exhaustive `match` | Generated client |
| [Resource routes](https://nijasc.github.io/ktor-svelte/features/typescript#resource-routes) | `resource` registers list, get, create, update and delete with the names the client expects | Ktor plugin |
| [Routes nothing calls](https://nijasc.github.io/ktor-svelte/features/typescript#routes-nothing-calls) | `svelteVerifyApiRoutes` lists API routes the frontend never uses | Gradle |
| [What changed for callers](https://nijasc.github.io/ktor-svelte/features/typescript#what-changed-for-callers) | `svelteApiChanges` compares the API with another git revision | Gradle |
| [Generator playground](https://nijasc.github.io/ktor-svelte/features/playground) | Paste an OpenAPI document and see the TypeScript it becomes, in the browser | This site |
### Calling the API
| Feature | What it does | Where it lives |
|---|---|---|
| [Typed calls and errors](https://nijasc.github.io/ktor-svelte/features/calling-the-api) | `api.notes.list()`, `isApiError`, `isValidationError`, `errorMessage`, event streams and uploads | Generated client |
| [Prefetch on hover](https://nijasc.github.io/ktor-svelte/features/calling-the-api#prefetch-on-hover) | Load a page's data, or one call, while the pointer rests on a link | Generated client |
| [Error codes](https://nijasc.github.io/ktor-svelte/features/calling-the-api#error-codes) | Named errors from one Kotlin enum instead of status numbers | Ktor plugin, Generated client |
| [Query parameters as a class](https://nijasc.github.io/ktor-svelte/features/calling-the-api#query-parameters-as-a-class) | `call.query()` reads the query string into a class, and the client gets its type | Ktor plugin |
| [Changing some fields](https://nijasc.github.io/ktor-svelte/features/calling-the-api#changing-some-fields) | `Patch` for `PATCH` routes that tell "not sent" from "set to null" | Ktor plugin, Generated client |
| [Two people, one record](https://nijasc.github.io/ktor-svelte/features/calling-the-api#two-people-one-record) | A version check that refuses a save over someone else's change | Ktor plugin, Generated client |
| [Path parameters](https://nijasc.github.io/ktor-svelte/reference/ktor#path-parameters) | `call.pathParameter(name)` reads a path parameter as a number, UUID or enum | Ktor plugin |
| [Paged lists](https://nijasc.github.io/ktor-svelte/recipes/pagination) | `Page` and `getPage` on the server, `pages()` in the browser | Ktor plugin, Generated client |
| [Only some fields](https://nijasc.github.io/ktor-svelte/features/calling-the-api#only-some-fields) | `?fields=id,title` sends only those fields, and the client's return type narrows to them | Ktor plugin, Generated client |
| [Included relations](https://nijasc.github.io/ktor-svelte/features/calling-the-api#included-relations) | `?include=author` adds related objects, typed so the field exists only when asked for | Ktor plugin, Generated client |
| [Uploads](https://nijasc.github.io/ktor-svelte/recipes/uploads) | `FormData` bodies with upload progress, and size and type rules shared by both sides | Ktor plugin, Generated client |
| [Live updates](https://nijasc.github.io/ktor-svelte/recipes/live-updates) | Server-sent events become async generators in the client | Ktor plugin, Generated client |
| [In load functions](https://nijasc.github.io/ktor-svelte/features/calling-the-api#in-load-functions) | `apiWith(event)` runs every call through SvelteKit's `fetch` | Generated client |
| [Refresh the page after a write](https://nijasc.github.io/ktor-svelte/features/calling-the-api#refresh-the-page-after-a-write) | `onWrite` reruns the page's `load` functions after a successful write | Generated client |
| [Ask before a call](https://nijasc.github.io/ktor-svelte/features/calling-the-api#ask-before-a-call) | `confirmed` asks first and only calls on yes | Generated client |
| [Show errors automatically](https://nijasc.github.io/ktor-svelte/features/calling-the-api#show-errors-automatically) | Every failed call shows a toast, with no error handling in components | Gradle, Generated client |
| [Toasts from the server](https://nijasc.github.io/ktor-svelte/features/calling-the-api#toasts-from-the-server) | `call.toast(...)` in a route shows a message in the browser | Ktor plugin |
| [Navigation from the server](https://nijasc.github.io/ktor-svelte/features/calling-the-api#navigation-from-the-server) | `call.navigateTo(...)` tells the browser which page to open next | Ktor plugin |
| [Reload after a deploy](https://nijasc.github.io/ktor-svelte/features/calling-the-api#reload-after-a-deploy) | The client notices a new build and can offer a reload | Ktor plugin, Generated client |
| [Request IDs](https://nijasc.github.io/ktor-svelte/features/calling-the-api#request-ids) | Every call carries an `X-Request-Id` that reaches your logs and the error | Ktor plugin, Generated client |
| [Timeouts](https://nijasc.github.io/ktor-svelte/features/calling-the-api#timeouts) | One timeout for every call, or one per call | Generated client |
| [Retries](https://nijasc.github.io/ktor-svelte/features/calling-the-api#retries) | GET requests that failed on the network are tried again | Generated client |
| [Rate limits](https://nijasc.github.io/ktor-svelte/features/calling-the-api#rate-limits) | `isRateLimitError` and `retryAfter`, and with retries on, one automatic wait and retry | Generated client |
| [Writes that are safe to send twice](https://nijasc.github.io/ktor-svelte/features/calling-the-api#writes-that-are-safe-to-send-twice) | Idempotency keys, so a repeated write is answered once | Ktor plugin, Generated client |
| [The visitor's time zone](https://nijasc.github.io/ktor-svelte/features/calling-the-api#the-visitor-s-time-zone) | `call.timeZone` in every route, sent by the client | Ktor plugin, Generated client |
| [Search as you type](https://nijasc.github.io/ktor-svelte/features/calling-the-api#search-as-you-type) | `latest` aborts the previous call, so an old answer never wins | Generated client |
| [Fixtures for frontend tests](https://nijasc.github.io/ktor-svelte/features/calling-the-api#fixtures-for-frontend-tests) | Record real answers in the dev panel and replay them without a backend | Generated client |
### Validation and forms
| Feature | What it does | Where it lives |
|---|---|---|
| [Validation](https://nijasc.github.io/ktor-svelte/features/validation) | `@JsonSchema` bounds and `Validated` rules, checked on every `receive`, with field errors in a 422 and the same bounds in the browser | Ktor plugin, Generated client |
| [Cleaning up input](https://nijasc.github.io/ktor-svelte/features/validation#cleaning-up-input) | `@Trim`, `@Lowercase` and `@EmptyAsNull`, declared on the field | Ktor plugin |
| [Sensitive fields](https://nijasc.github.io/ktor-svelte/features/validation#sensitive-fields) | Mark a password or token once, and the dev tools show `***` | Ktor plugin |
| [Form state](https://nijasc.github.io/ktor-svelte/features/validation#form-state) | `formState` holds the values, changes, submit state and errors of a form | Generated client |
| [Checks only the server can make](https://nijasc.github.io/ktor-svelte/features/validation#checks-only-the-server-can-make) | "Is this email taken?" while the visitor types | Ktor plugin, Generated client |
### Config and transport
| Feature | What it does | Where it lives |
|---|---|---|
| [Runtime config](https://nijasc.github.io/ktor-svelte/features/runtime-config) | `publicConfig` passes values to the frontend at startup, inlined into every page | Ktor plugin, Generated client |
| [Changing values without a restart](https://nijasc.github.io/ktor-svelte/features/runtime-config#changing-values-without-a-restart) | Pass a function, and development picks up edits on the next page load | Ktor plugin |
| [Environment variables](https://nijasc.github.io/ktor-svelte/features/runtime-config#environment-variables) | `environment` declares every variable in one place, with types and a `.env.example` | Ktor plugin, Gradle |
| [Secrets in the frontend build](https://nijasc.github.io/ktor-svelte/features/runtime-config#secrets-in-the-frontend-build) | `svelteVerifyLeaks` fails the build when a secret reached the built files | Gradle |
| [Transport](https://nijasc.github.io/ktor-svelte/features/transport) | `json()`, `xml()`, other formats and `compression()` in one block | Ktor plugin |
| [API compression](https://nijasc.github.io/ktor-svelte/features/transport#api-compression) | API responses compressed by default, with zstd when you add it | Ktor plugin |
## Frontend
Pages, links, styling and components, turned on in Gradle and typed on both sides. [Frontend libraries](https://nijasc.github.io/ktor-svelte/features/frontend-libraries) is the overview of every library.
### Pages and links
| Feature | What it does | Where it lives |
|---|---|---|
| [Typed routes](https://nijasc.github.io/ktor-svelte/features/routes) | Every page as a typed constant: `routes` in Svelte, `FrontendRoutes` in Kotlin | Gradle, Generated client |
| [Marking the open page](https://nijasc.github.io/ktor-svelte/features/routes#marking-the-open-page-in-a-menu) | `isActive` for menus, without comparing paths | Generated client |
| [Menu, titles and breadcrumbs](https://nijasc.github.io/ktor-svelte/features/routes#menu-titles-and-breadcrumbs) | Each page says its own title and icon in `+page.ts` | Gradle, Generated client |
| [Link previews](https://nijasc.github.io/ktor-svelte/features/routes#link-previews) | Tags for chat and social previews, from the same page metadata | Gradle, Generated client |
| [A new page](https://nijasc.github.io/ktor-svelte/features/routes#a-new-page) | `svelteAdd --page` writes a page with a typed load | Gradle |
| [Pages for a class](https://nijasc.github.io/ktor-svelte/features/routes#pages-for-a-class) | `svelteAdd --crud` writes list, detail and form pages from the generated client | Gradle |
| [Renaming a page](https://nijasc.github.io/ktor-svelte/features/routes#renaming-a-page) | `svelteRename` moves a page and fixes every typed call to it | Gradle |
| [Links that are still strings](https://nijasc.github.io/ktor-svelte/features/routes#finding-links-that-are-still-strings) | `svelteVerifyRoutes` finds string links and suggests the typed call | Gradle |
| [Links that lead nowhere](https://nijasc.github.io/ktor-svelte/features/routes#finding-links-that-lead-nowhere) | `svelteVerifyLinks` finds links to pages that do not exist | Gradle |
### Look and feel
| Feature | What it does | Where it lives |
|---|---|---|
| [Tailwind](https://nijasc.github.io/ktor-svelte/features/styling#tailwind) | Tailwind 4 in Vite and the CSS, with the typography and forms plugins | Gradle |
| [DaisyUI themes](https://nijasc.github.io/ktor-svelte/features/styling#daisyui) | Components and themes, typed in TypeScript and Kotlin, with no flash of the wrong theme | Gradle, Generated client |
| [shadcn themes](https://nijasc.github.io/ktor-svelte/features/styling#shadcn-themes) | The shadcn/ui look for every DaisyUI component | Gradle |
| [Custom themes](https://nijasc.github.io/ktor-svelte/features/styling#custom-themes) | Your own colors, and a dev panel editor to tune them live | Gradle |
| [Fonts](https://nijasc.github.io/ktor-svelte/features/styling#fonts) | A font served from your own app, preloaded | Gradle |
| [Lucide icons](https://nijasc.github.io/ktor-svelte/features/icons-and-images#lucide-icons) | A typed `LucideIcon` enum and an `` component, with only the icons you use | Gradle, Generated client |
| [Images](https://nijasc.github.io/ktor-svelte/features/icons-and-images#images) | `` with AVIF and WebP in several widths | Gradle |
| [Charts](https://nijasc.github.io/ktor-svelte/features/charts) | LayerChart in your theme colors, with typed series | Gradle, Generated client |
| [Installable app](https://nijasc.github.io/ktor-svelte/features/installable-app) | A web manifest, icons, a service worker and an offline page | Gradle, Ktor plugin |
| [Emails](https://nijasc.github.io/ktor-svelte/features/emails) | Svelte components rendered to HTML and text emails at build time, with a typed Kotlin function per email | Gradle |
### Languages
| Feature | What it does | Where it lives |
|---|---|---|
| [i18n](https://nijasc.github.io/ktor-svelte/features/i18n) | Typed messages from one JSON file per language, in Svelte and in Kotlin | Gradle, Generated client |
| [Strategies](https://nijasc.github.io/ktor-svelte/features/i18n#strategies) | The language from a cookie or from a URL prefix | Gradle |
| [Plurals](https://nijasc.github.io/ktor-svelte/features/i18n#plurals) | "1 note" and "2 notes" as one message | Gradle, Generated client |
| [Numbers, money and dates](https://nijasc.github.io/ktor-svelte/features/i18n#numbers-money-and-dates) | Formats that read the same in the browser and on the server | Gradle, Generated client |
| [Relative time](https://nijasc.github.io/ktor-svelte/features/i18n#relative-time) | "3 minutes ago", in the visitor's language | Generated client |
| [Messages nobody translated yet](https://nijasc.github.io/ktor-svelte/features/i18n#messages-nobody-translated-yet) | The dev panel marks copied, untranslated texts | Gradle |
| [Messages nothing uses](https://nijasc.github.io/ktor-svelte/features/i18n#messages-nothing-uses) | `svelteVerifyMessages` lists keys you can delete | Gradle |
### Components
| Feature | What it does | Where it lives |
|---|---|---|
| [Components](https://nijasc.github.io/ktor-svelte/features/components) | Svelte components over the generated helpers, imported as `#components/...` | Gradle, Generated client |
| [Field](https://nijasc.github.io/ktor-svelte/features/components#field) | Label, input, hint and validation errors in one | Generated client |
| [DateInput and DateTimeInput](https://nijasc.github.io/ktor-svelte/features/components#dateinput-and-datetimeinput) | Inputs that bind to `IsoDate` and `IsoDateTime` | Generated client |
| [EnumSelect](https://nijasc.github.io/ktor-svelte/features/components#enumselect) | A `