Skip to content

Ktor settings ​

Every setting of install(Svelte) { }, grouped by topic, with its default. To pick settings with checkboxes instead, use the configurator. To see the settings your app really runs with, run ./gradlew svelteConfig.

Ktor plugin

All defaults at a glance ​

The values shown are the defaults.

kotlin
install(Svelte) {
    apiPrefixes("/api")
    paramRoutes()
    spaFallback = "200.html"
    notFoundPage = "404.html"
    source = SvelteSource.Classpath
    generateTs = false
    generateTsOutput = null
    apiDocs = false
    apiDocsPath = "/api/docs"
    routing = SvelteRouting.Automatic
    loginPage = null
    statusEndpoint = false
    internalAccess { }
    healthEndpoint = false
    warmUp()
    originCheck = true
    hideErrorDetails = true
    apiCompression = true
    mailer = null
    inlinePublicConfig = true
    buildHeader = true
    requestIds = true
    accessLog = false
    publicBuildInfo = false
    defaultTimeZone = "UTC"
    allowedOrigins()
    maxApiBodySize = 1048576
    maxJsonDepth = 64
    maxJsonStringLength = null
    sitemap = true
    defaultFavicon = true
    siteUrl = null

    securityHeaders {
        enabled = true
        contentTypeOptions = "nosniff"
        frameOptions = "DENY"
        referrerPolicy = "strict-origin-when-cross-origin"
        contentSecurityPolicy = null
        automaticContentSecurityPolicy = true
    }

    cache {
        immutable = "public, max-age=31536000, immutable"
        html = "no-cache"
        other = "no-cache"
    }

    dev {
        url = "http://localhost:5173"
        mode = DevMode.Auto
        allowRemote = false
        slowApiCall = 500.milliseconds
        panel = true
        browserLogs = true
        refreshAfterRestart = true
        errorOverlay = true
        startupTiming = true
        catchEmails = true
    }

    rateLimit {
        enabled = true
        apiWrites = 120
        period = 1.minutes
        algorithm = RateLimitAlgorithm.FixedWindow
    }

    transport {
    }
}

Features that are off until you call them, such as frontendErrors(), webVitals(), idempotency(), currentUser, guards or errorCodes, are in the tables below.

Serving the frontend ​

SettingDefaultWhat it does
apiPrefixes(...)"/api"Paths the frontend never answers, and the routes included in generateTs. /api matches /api and /api/x, not /apiary
paramRoutes(...)noneSvelteKit route patterns such as /items/[id], /docs/[...rest] and /blog/[[page]]. Matching paths get the fallback even when the request does not accept HTML, for example link previews or tests. Paths with a file extension still return 404. Also used to group page timings
spaFallback"200.html"Page for client-side routes. Must match the adapter's fallback option. null disables it
notFoundPage"404.html"Page served with status 404. null disables it
sourceSvelteSource.ClasspathWhere the build comes from. SvelteSource.Directory(path) serves a build from disk
routingSvelteRouting.AutomaticManual lets you place the frontend yourself with svelte(), for example behind authentication. See Auth
cache { }see belowCache-Control values
frontend(prefix) { }noneAnother SvelteKit build served under a path prefix such as "/admin", with its own source, spaFallback, notFoundPage, paramRoutes, devUrl and generateTsOutput. See Multiple frontends
sitemaptrueServes a generated /sitemap.xml and /robots.txt when the build has none. See Sitemap and robots.txt
siteUrlnullPublic address used in the sitemap, such as https://example.com. null takes it from the request
defaultFavicontrueServes a ktor-svelte favicon while the app has none of its own. See Default favicon

cache ​

SettingDefaultUsed for
immutable"public, max-age=31536000, immutable"Hashed files under _app/immutable/**
html"no-cache"HTML pages
other"no-cache"Every other file
kotlin
install(Svelte) {
    paramRoutes("/notes/[id]", "/docs/[...rest]")
    cache {
        other = "public, max-age=3600"
    }
}

Generated TypeScript and API docs ​

SettingDefaultWhat it does
generateTsfalseGenerates TypeScript from your routes in development mode. See Generated TypeScript
generateTsOutputnullOutput directory. null means src/lib/api in your frontend
apiDocsfalseServes Swagger UI in development mode, and elsewhere when internalAccess is set. See API docs
apiDocsPath"/api/docs"Path of the Swagger UI page
errorResponse<T>(statuses)noneDeclares an error body that handlers outside your routes send, so the generated client types it. Takes status codes of 400 and above. See Calling the API
errorCodes<E>(message)noneOne enum of named error codes for the whole app, optionally with a message for each. See Error codes
constants(...)noneKotlin objects whose values are copied into the frontend. See Shared constants
cookies(...)noneTyped cookies that both sides read and write. A name may be declared once

Runtime config ​

SettingDefaultWhat it does
publicConfig(value)noneValues for the frontend. publicConfig { ... } reads them again on every request in development. See Runtime config
inlinePublicConfigtruePuts the public config into every page, so the frontend has it without a request
defaultTimeZone"UTC"What call.timeZone returns when a request does not say which zone the visitor is in

Users and sign-in ​

SettingDefaultWhat it does
currentUser<T>(path, signInMessage, sessionEnds, extendSession) { find }noneHow the server finds the signed-in user. Served at /api/current-user (under your first API prefix) unless you pass path. See The current user
permissions<P, U>(refusedMessage) { of }noneOne enum of permissions and how to read a user's set. See Permissions
guards { }noneWhich pages need a signed-in user (signedIn(...)) or a permission (permission(p, ...)). Closes the API below the same name too. See Page guards
preferences<T, U>(defaults, path, load, save)nonePer-user preferences kept on the server. Served at /api/preferences unless you pass path. See User preferences
loginPagenullPath of the login page. A 401 from the API then opens it with the current page as next. See The login page

An app has one currentUser, one permissions enum, one errorCodes enum and one preferences class. Declaring one twice fails at startup.

Security ​

SettingDefaultWhat it does
originChecktrueRefuses cross-site requests to API paths for every method except GET, HEAD, OPTIONS and TRACE. See API request guards
allowedOrigins(...)noneExtra origins, such as https://admin.example.com, that may write to the API
maxApiBodySize1048576 (1 MiB)Largest request body on API paths, in bytes. null disables it
maxJsonDepth64Refuses JSON request bodies on API paths that nest deeper than this, with 400. null turns it off
maxJsonStringLengthnullRefuses JSON request bodies on API paths with a longer string, with 400. Off by default
hideErrorDetailstrueAnswers unhandled exceptions in production without their message. See API request guards
securityHeaders { }see belowSecurity headers and the Content-Security-Policy
rateLimit { }see belowLimits API writes per client, and holds named limits
idempotency { }offAnswers a repeated Idempotency-Key with the stored first answer. See Writes that are safe to send twice

securityHeaders ​

See Security headers.

SettingDefaultWhat it does
enabledtrueSends security headers. false turns all of them off
contentTypeOptions"nosniff"X-Content-Type-Options. null leaves it out
frameOptions"DENY"X-Frame-Options. null leaves it out
referrerPolicy"strict-origin-when-cross-origin"Referrer-Policy. null leaves it out
contentSecurityPolicynullYour own policy, sent unchanged on every response. null uses the automatic policy
automaticContentSecurityPolicytrueSends a strict CSP built from the inline scripts of each HTML page
allowCspSources(directive, sources)noneAdds sources to one directive of the automatic policy
kotlin
install(Svelte) {
    securityHeaders {
        allowCspSources("img-src", "https://images.example.com")
    }
}

rateLimit ​

See API request guards.

SettingDefaultWhat it does
enabledtruefalse removes the default limit and lets you install Ktor's RateLimit yourself
apiWrites120Writes per client and period on API paths. 0 keeps the named limits but drops the default one
period1.minutesThe period of the default limit
algorithmRateLimitAlgorithm.FixedWindowFixedWindow, SlidingWindow or TokenBucket
key { call -> }the client addressWhat tells clients apart, for every limit
limit(name, requests, per, algorithm, key)noneA named limit for Ktor's rateLimit(RateLimitName(name)), such as for login

idempotency ​

SettingDefaultWhat it does
ttl10.minutesHow long an answer is kept. Must be above zero
maxEntries10000How many answers are kept in memory. At least 1

Responses ​

SettingDefaultWhat it does
apiCompressiontrueCompresses API responses of 1 KiB or more with gzip, deflate or zstd. See API compression
transport { }nothing installedJSON, XML and compression: json { }, xml(), negotiation { }, compression { }. See Transport
mailernullThe Mailer that sends application.mailer emails outside development. See Emails
buildHeadertrueSends the frontend build fingerprint on API responses as X-Ktor-Svelte-Build, so the client can notice a deploy
requestIdstrueGives every request an X-Request-Id, keeps one sent by the client and logs it with unhandled errors

Built-in endpoints ​

See Built-in endpoints.

SettingDefaultWhat it does
healthEndpointfalseServes /_ktor-svelte/health for load balancers and orchestrators. See Health endpoint
warmUp(...)nonePaths the app calls on itself once the port is open, before the health endpoint reports it up. See Warm-up before ready
healthCheck { }noneAdds a check of your own. Every check must return true for the app to be up
statusEndpointfalseServes build and proxy details at /_ktor-svelte/status, to this machine only. See Status endpoint
internalAccess { }this machine onlyWho may see the status endpoint and the API docs besides this machine: a token, networks(...) or your own allow { } check. See Who may see internal endpoints
publicBuildInfofalseServes the app's build info at /_ktor-svelte/build.json, for loadBuildInfo() in the browser. Off because it tells every visitor the version and the commit

Monitoring ​

See Monitoring.

SettingDefaultWhat it does
accessLogfalseLogs one line per request in production to the ktor-svelte.access logger: method=GET path=/api/notes status=200 ms=12 id=.... The query string is left out, because it can hold secrets, and requests for build assets under /_app/ are skipped. Development mode never logs these
frontendErrors { }offBrowsers report uncaught errors to the ktor-svelte.frontend logger. Settings: perClientPerMinute = 10, maxBodyBytes = 8192 (256 to 65536)
webVitals { }offBrowsers report page timings into svelteMetrics. Settings: sampleRate = 0.1 (above 0, at most 1), perClientPerMinute = 10

Development ​

See Dev workflow.

SettingDefaultWhat it does
dev.url"http://localhost:5173"Vite URL. The KTOR_SVELTE_DEV_SERVER environment variable overrides it
dev.modeDevMode.AutoAuto follows Ktor's development mode. Always and Never force it
dev.allowRemotefalseLets other machines use the dev proxy, and lets dev.url point at another machine
dev.slowApiCall500.millisecondsLogs API calls that take longer than this in development. null turns it off
dev.paneltrueShows the dev panel of recent API calls, with status, timing and validation errors, on pages proxied from Vite
dev.browserLogstrueSends browser console output, uncaught errors and unhandled rejections from pages proxied from Vite to the app's log
dev.refreshAfterRestarttrueAfter the app restarts in development, open pages rerun their load functions, so a Kotlin change shows up without a manual reload
dev.errorOverlaytrueShows the Kotlin exception of a failed API call in the browser, in development. Needs dev.panel
dev.catchEmailstrueIn development, application.mailer keeps emails for the dev panel instead of sending them
dev.startupTimingtrueLogs what the startup time was spent on in development, with the parts you wrapped in startupStep

Route.svelte() ​

With routing = SvelteRouting.Manual, you place the frontend in your own routing. Call install(Svelte) first.

CallWhat it does
svelte()Serves the frontend for every path under this route. Pages get private caching, so shared proxies do not keep them
svelte(public = listOf(...))Serves only the listed paths, with normal caching. A path ending in /* covers everything below it
kotlin
routing {
    svelte(public = listOf("/login", "/_app/*"))
    authenticate("session") {
        svelte()
    }
}

The public list must include your login page and /_app/*, or the login page cannot load. In development mode, svelte(public = ...) also opens the paths Vite needs, so hot reload works on your login page. The files of an installable app, such as /service-worker.js and /ktor-svelte/*, stay public too, since a browser fetches them without a session. See Auth.

Functions for your routes ​

Besides the settings, the plugin gives your routes these helpers:

FunctionWhat it doesSee
call.pathParameter<T>(name)Reads a path parameter in the type you needPath parameters
call.timeZoneThe visitor's time zone, or defaultTimeZoneThe visitor's time zone
call.toast(...)Sends a toast with the answerToasts from the server
call.navigateTo(path)Tells the client to go to a page after the callNavigation from the server
call.respondIfStale(sent, current) { record }Answers 409 with the current record when the write was based on an old versionTwo people, one record
call.requireOwner(record) { user: User, record -> ... }Returns the record when it belongs to the caller, answers 404, 401 or 403 otherwise; route.ownerChecked() describes those answersOwner checks
call.respondLoginRedirect()Redirects to loginPage, carrying the current pageThe login page
route.timeout(30.seconds)Cancels the handler after the limit with a 503, and makes the generated call use it as its timeoutA time limit per route
getPage<T>(path) { }A paged GET route with cursor and limitPage through long lists
resource<T, ID>(path) { }The routes of one class, declared in one blockResource routes
application.buildInfoVersion, commit and commit time of the buildBuild info
application.mailer.send(Email(...))Sends an email through mailer, or catches it for the dev panel in developmentEmails
application.svelteMetricsRefusal counters and web vitalsMonitoring
startupStep(name) { }Names a part of startup for the dev startup logStartup timing

Path parameters ​

call.pathParameter<T>(name) reads a path parameter in the type you need, so a route does not parse it by hand:

kotlin
get("/api/notes/{id}") {
    val id = call.pathParameter<Int>("id")
    call.respond(store.create(Note(id, "x")))
}
TypeReads
StringThe text as it is
Int, LongA whole number
UUIDA UUID
An enumA constant by name, in any case

A value that does not fit, such as /api/notes/abc, ends the request with Ktor's NotFoundException: the address names nothing, so the answer is 404, through your StatusPages if you have one. Asking for a parameter the route's path does not have, or for a type it cannot read, is a mistake in the route and fails with a 500 that says so.

Good to know ​

  • A route of yours such as get("/{slug}") beats the frontend. That is intended, but it can hide pages. The app logs it: "the Ktor route GET /about hides the frontend page about.html. Move the route or rename the page."
  • ETags are content hashes from the manifest, so 304 responses are cheap and stay valid across restarts.
  • If you set adapter({ precompress: true }), the .br and .gz files are served based on Accept-Encoding. Files the adapter did not compress, such as those from static/, are gzipped by svelteBundle unless you set precompress = false in Gradle. .zst files next to them, for example from a Vite compression plugin, are bundled too and preferred for browsers that accept zstd, since they decompress faster.
  • If the frontend build is missing, the app fails at startup in production with a message explaining what to do. In Ktor development mode it logs a warning instead, and frontend routes return a 503 explaining the problem.
  • ktor-svelte installs Ktor's RequestBodyLimit and RateLimit itself. To use your own, set maxApiBodySize = null or rateLimit { enabled = false }. The same goes for ContentNegotiation and Compression when you use transport { }.

Documentation for ktor-svelte 1.4.0. Released under the Apache 2.0 license.