Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Plugins and Serialization

Logging, CORS and Compression

Configure three everyday Ktor plugins: CallLogging with call IDs, CORS rules for browser front ends, and gzip Compression, with a stand-in showing the CORS rules and gzip savings.

Three plugins show up in almost every production Ktor server: one to see what the server does (logging), one to let browsers on other origins call it (CORS), and one to make responses smaller (compression). This lesson configures each, explains the reasoning behind the settings, and runs stand-ins for the two with logic you can test: CORS decisions and gzip savings.

Logging with CallLogging and CallId

Ktor logs through SLF4J, and the usual backend is Logback (logback-classic). The CallLogging plugin logs one line per request:

Kotlin
import io.ktor.server.plugins.calllogging.*
import io.ktor.server.plugins.callid.*
import org.slf4j.event.Level

fun Application.module() {
    install(CallId) {
        header(HttpHeaders.XRequestId)           // reuse the client's/gateway's ID if present
        generate { java.util.UUID.randomUUID().toString() }   // otherwise create one
        verify { it.isNotEmpty() }
    }
    install(CallLogging) {
        level = Level.INFO
        callIdMdc("call-id")                     // put the ID into every log line
        filter { call -> call.request.path().startsWith("/api") }   // skip /health noise
    }
}

CallId gives every request a correlation ID, and callIdMdc places it in the logging context so you can search the logs for one request across all log lines. Reuse an incoming X-Request-Id so one ID follows a request through load balancer, gateway and several services. Add %X{call-id} to the Logback pattern in src/main/resources/logback.xml:

TEXT
<pattern>%d{HH:mm:ss.SSS} %-5level [%X{call-id}] %logger{20} - %msg%n</pattern>

Inside handlers use the application logger: call.application.log.info("User ${id} created"). Rules of thumb: log at INFO for important events, WARN for recoverable problems, ERROR for failures, never log passwords, tokens or full card numbers, and keep health checks out of the request log.

CORS

Browsers enforce the same-origin policy: JavaScript on https://app.example.com may not read responses from https://api.example.com unless the API says it is fine, using CORS headers. This is a browser rule; curl and server-to-server calls ignore it. Install the plugin when a front end served from another origin calls your API:

Kotlin
import io.ktor.server.plugins.cors.routing.*

install(CORS) {
    allowHost("app.example.com", schemes = listOf("https"))
    allowHost("localhost:3000")                      // local front-end development
    allowMethod(HttpMethod.Put)
    allowMethod(HttpMethod.Delete)
    allowHeader(HttpHeaders.Authorization)
    allowHeader(HttpHeaders.ContentType)
    allowCredentials = true                          // allow cookies / Authorization
    maxAgeInSeconds = 3600                           // cache preflight answers for an hour
}

How it works: for "simple" requests the browser sends an Origin header, and the server answers Access-Control-Allow-Origin. For anything else (a PUT, a JSON POST, an Authorization header) the browser first sends a preflight OPTIONS request asking permission; Ktor's plugin answers it, and the real request follows.

anyHost() allows every origin and is acceptable only for fully public, credential-free APIs. Combined with allowCredentials it is dangerous, and browsers refuse a wildcard with credentials anyway. List your real front-end origins.

Compression

JSON and HTML compress very well. The Compression plugin applies gzip (or deflate) when the client sends Accept-Encoding: gzip:

Kotlin
import io.ktor.server.plugins.compression.*

install(Compression) {
    gzip { priority = 1.0 }
    deflate { priority = 10.0 }
    minimumSize(1024)                      // do not bother below 1 KB
    excludeContentType(ContentType.Video.Any, ContentType.Image.PNG)
}

Already-compressed formats (PNG, JPEG, MP4, ZIP) gain nothing, so exclude them. In production a reverse proxy (nginx, a CDN) often compresses instead; do it in only one place.

Stand-in: CORS decisions and gzip savings

The first part implements the CORS decision logic: given an allow-list and a request, which headers does the server send, and how is a preflight answered? The second part uses the JDK's real GZIPOutputStream to measure how much a JSON array shrinks.

Kotlin Stand-in: CORS decisions and gzip size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last line shows why minimumSize exists: gzip of a tiny body is bigger than the original.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a CORS preflight request?

    For non-simple requests the browser asks first with OPTIONS.
  2. 2. Does CORS protect your API from curl or other servers?

    CORS only controls what browser JavaScript may read; it is not access control.
  3. 3. Why set minimumSize for Compression?

    Compressing tiny bodies wastes CPU and can increase size.
  4. 4. What is the purpose of a call ID (correlation ID)?

    The ID, placed in the logging context, ties together every log line of a request.

Summary

  • CallLogging plus CallId log requests with a correlation ID; keep secrets and health checks out of logs.
  • CORS lists the exact front-end origins, methods and headers the browser may use; it handles preflight automatically.
  • Compression gzips large, compressible bodies; skip small and already-compressed ones.
  • Install these before routing; they apply to every call.

Plugins are in place. Next you will protect routes: the authentication chapter.

Next: Authentication Basics