Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Plugins and Serialization

Plugins and Interceptors

Understand Ktor plugins: install built-in ones, scope them to routes, and write custom plugins with createApplicationPlugin, onCall and onCallRespond hooks.

Ktor's core is tiny by design. JSON conversion, logging, authentication, compression, CORS, sessions and many other features are plugins: pieces of code that hook into the request pipeline you saw in How Ktor Handles a Request. You install the ones you need and nothing else. In this lesson you will learn how to install plugins, how to scope them to part of your routes, and how to write your own.

Installing a plugin

Plugins are installed in a module with install. Many have a configuration block:

Kotlin
fun Application.module() {
    install(CallLogging)                       // no configuration
    install(Compression) {                     // with configuration
        gzip { priority = 1.0 }
        deflate { priority = 10.0 }
    }
    install(DefaultHeaders) {
        header("X-Engine", "Ktor")
    }
    routing { /* ... */ }
}

Each plugin lives in its own dependency (ktor-server-call-logging, ktor-server-compression, and so on) so your JAR contains only what you use. Order matters when plugins interact: install anything that should see every call (logging, call IDs, status pages) before routing.

Some plugins are installed implicitly by a DSL function. For example routing { } installs the Routing plugin and authenticate("x") { } relies on Authentication, which you must install yourself first. Forgetting it produces a start-up or call-time error such as "Plugin Authentication is not installed".

Built-in plugins at a glance

Plugin Purpose
ContentNegotiation Convert bodies to and from JSON and other formats
StatusPages Turn exceptions and status codes into responses
CallLogging Log each request
CallId Attach a correlation ID to each call
Compression gzip / deflate responses
CORS Cross-origin resource sharing rules
DefaultHeaders Add headers to every response
RequestValidation Validate request bodies
Authentication Credentials checking
Sessions Cookie or header based sessions
RateLimit Limit requests per client
WebSockets WebSocket support

The following lessons cover the ones used in almost every project.

Scoping a plugin to routes

Some plugins make sense for part of the API only. You can install them inside a route, and they then apply only to that subtree:

Kotlin
routing {
    route("/api") {
        install(RateLimitPlugin)       // only /api/** is rate limited
        get("/data") { /* ... */ }
    }
    get("/health") { /* not rate limited */ }
}

Only plugins designed for it can be installed on a route (they say so in their documentation). authenticate { }, shown in the authentication chapter, is the most common example.

Writing a plugin

When you find yourself repeating code in many handlers (timing, headers, a feature flag), write a plugin. createApplicationPlugin is the simplest API:

Kotlin
val RequestTimer = createApplicationPlugin(name = "RequestTimer") {
    onCall { call ->
        call.attributes.put(StartKey, System.nanoTime())
    }
    onCallRespond { call, _ ->
        val started = call.attributes[StartKey]
        val ms = (System.nanoTime() - started) / 1_000_000
        call.response.headers.append("X-Time-Ms", ms.toString())
    }
}
private val StartKey = AttributeKey<Long>("start")

fun Application.module() {
    install(RequestTimer)
}

The hooks you can use:

  • onCall runs when a call arrives, before routing. Good for reading headers and storing values in call.attributes.
  • onCallReceive can transform the incoming body before your handler gets it.
  • onCallRespond runs just before the response is sent. Good for adding headers or transforming the response body.
  • on(...) attaches to a custom hook, such as AuthenticationChecked, for advanced cases.

A plugin can accept configuration by supplying a configuration class and a block, exactly like the built-in ones:

Kotlin
class AuditConfig {
    var header: String = "X-Audit"
}

val Audit = createApplicationPlugin("Audit", ::AuditConfig) {
    val headerName = pluginConfig.header
    onCallRespond { call, _ -> call.response.headers.append(headerName, "seen") }
}

// install(Audit) { header = "X-Seen-By" }

call.attributes is a small type-safe key-value bag attached to each call. It is the correct place to pass data between plugins and handlers, for example a request ID, instead of global variables.

Stand-in: hooks that wrap the handler

The stand-in below implements onCall and onCallRespond hooks, a call attributes bag, plugin configuration and install. It then installs a timing plugin, a request-ID plugin and a configurable header plugin, and processes a few calls.

Kotlin Stand-in: onCall / onCallRespond plugins

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.

Because each plugin adds code around the handler without the handler knowing, you can add or remove features by changing one install line.

Practical advice

  • Keep plugins focused: one concern each.
  • Use call.attributes to share data, not mutable globals (calls run concurrently).
  • Put cross-cutting code that needs route-specific decisions in a plugin installed on that route.
  • For everything that already exists, use the official plugin; write your own only for app-specific rules.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should a plugin that must see every call (such as logging) be installed?

    Install it at the application level, before routing, so it wraps all calls.
  2. 2. Which hook runs just before the response is sent?

    onCallRespond lets you add headers or transform the response.
  3. 3. What is call.attributes for?

    Attributes hold per-call state such as a request ID or start time.
  4. 4. How do you limit a plugin to the routes under /api?

    Route-scoped plugins are installed inside a route block and apply to that subtree.

Summary

  • Plugins add features to the pipeline; install them with install(Plugin) { config }, before routing.
  • Some plugins can be scoped to a route subtree.
  • Write your own with createApplicationPlugin, using onCall and onCallRespond.
  • Use call.attributes for per-call state.

Next: Content Negotiation and JSON