HTTP middleware
suggest changeMiddleware is code that runs around every HTTP request handled by a server: before the route handler executes, after it produces a response, or both. Typical uses are logging, timing, request IDs, authentication checks, CORS, compression, security headers, and turning exceptions into error responses.
The core idea is simple: a middleware takes a handler and returns a new handler that wraps it. Kotlin frameworks give this different names - Ktor calls them plugins, http4k calls them filters, Spring calls them filters and interceptors - but the shape is the same.
The concept in plain Kotlin
Before looking at a framework, here is middleware as pure function composition. This compiles and runs with nothing but the Kotlin standard library:
data class Request(val method: String, val path: String, val headers: Map<String, String> = emptyMap())
data class Response(val status: Int, val body: String, val headers: Map<String, String> = emptyMap())
typealias Handler = (Request) -> Response
typealias Middleware = (Handler) -> Handler
// Runs code before and after the wrapped handler
val timing: Middleware = { next ->
{ req ->
val start = System.nanoTime()
val resp = next(req)
val ms = (System.nanoTime() - start) / 1_000_000
resp.copy(headers = resp.headers + ("X-Response-Time" to "${ms}ms"))
}
}
// Short-circuits: never calls next() if the request is not authorized
val requireAuth: Middleware = { next ->
{ req ->
if (req.headers["Authorization"] == "Bearer secret") next(req)
else Response(401, "Unauthorized")
}
}
// Converts exceptions into 500 responses
val recover: Middleware = { next ->
{ req ->
try {
next(req)
} catch (e: Exception) {
Response(500, "Internal error: ${e.message}")
}
}
}
// Compose: the first middleware in the list is the outermost one
fun Handler.with(vararg middlewares: Middleware): Handler =
middlewares.foldRight(this) { mw, acc -> mw(acc) }
fun main() {
val app: Handler = { req -> Response(200, "Hello from ${req.path}") }
val server = app.with(recover, timing, requireAuth)
println(server(Request("GET", "/hi")))
println(server(Request("GET", "/hi", mapOf("Authorization" to "Bearer secret"))))
}
Two things to notice:
- Order matters.
recoveris outermost, so it also catches exceptions thrown bytimingandrequireAuth. MovingrequireAuthbeforetimingwould mean rejected requests are not timed. - A middleware may short-circuit by returning a response without calling
next.
This is almost exactly http4k's model, where Filter is (HttpHandler) -> HttpHandler and filters are combined with then.
Middleware in Ktor: custom plugins
Ktor (3.x) is the most common Kotlin-native server framework. Add the dependencies to build.gradle.kts:
dependencies {
val ktorVersion = "3.6.0"
implementation("io.ktor:ktor-server-core:$ktorVersion")
implementation("io.ktor:ktor-server-netty:$ktorVersion")
implementation("io.ktor:ktor-server-call-logging:$ktorVersion")
implementation("io.ktor:ktor-server-call-id:$ktorVersion")
implementation("io.ktor:ktor-server-status-pages:$ktorVersion")
implementation("io.ktor:ktor-server-default-headers:$ktorVersion")
implementation("io.ktor:ktor-server-cors:$ktorVersion")
implementation("ch.qos.logback:logback-classic:1.6.5")
testImplementation("io.ktor:ktor-server-test-host:$ktorVersion")
testImplementation(kotlin("test"))
}
Custom middleware is written with createApplicationPlugin. Its builder exposes hooks such as onCall (before routing handles the request), onCallRespond (when a response is about to be sent), and on(ResponseSent) (after it was sent).
Request timing plugin
import io.ktor.server.application.*
import io.ktor.server.application.hooks.*
import io.ktor.server.request.*
import io.ktor.util.*
private val StartTimeKey = AttributeKey<Long>("StartTime")
val RequestTiming = createApplicationPlugin(name = "RequestTiming") {
onCall { call ->
call.attributes.put(StartTimeKey, System.nanoTime())
}
onCallRespond { call ->
val start = call.attributes.getOrNull(StartTimeKey) ?: return@onCallRespond
val ms = (System.nanoTime() - start) / 1_000_000
call.response.headers.append("X-Response-Time", "${ms}ms")
}
on(ResponseSent) { call ->
val start = call.attributes[StartTimeKey]
val ms = (System.nanoTime() - start) / 1_000_000
application.log.info("${call.request.httpMethod.value} ${call.request.uri} -> ${call.response.status()} in ${ms}ms")
}
}
call.attributes is a per-request type-safe map. It is the standard way to pass data from a middleware to later hooks or to route handlers.
Configurable plugins
Pass a configuration class with createConfiguration and read it through pluginConfig:
class SecurityHeadersConfig {
var frameOptions: String = "DENY"
var hsts: Boolean = true
}
val SecurityHeaders = createApplicationPlugin(
name = "SecurityHeaders",
createConfiguration = ::SecurityHeadersConfig
) {
val frameOptions = pluginConfig.frameOptions
val hsts = pluginConfig.hsts
onCall { call ->
call.response.headers.append("X-Frame-Options", frameOptions)
call.response.headers.append("X-Content-Type-Options", "nosniff")
if (hsts) {
call.response.headers.append("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
}
}
Read config values once in the plugin body (as above), not inside the hooks, so they are not re-read for every request.
Route-scoped plugins and short-circuiting
createRouteScopedPlugin creates middleware that can be installed on a subset of routes. Responding inside onCall marks the call as handled, and the route handler is not executed:
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
class ApiKeyConfig {
var headerName: String = "X-API-Key"
var validKeys: Set<String> = emptySet()
}
val RequireApiKey = createRouteScopedPlugin(
name = "RequireApiKey",
createConfiguration = ::ApiKeyConfig
) {
val headerName = pluginConfig.headerName
val validKeys = pluginConfig.validKeys
onCall { call ->
val key = call.request.headers[headerName]
if (key == null || key !in validKeys) {
call.respond(HttpStatusCode.Unauthorized, "Missing or invalid API key")
}
}
}
For real authentication prefer Ktor's Authentication plugin (see the Authentication and JWT articles); this pattern is useful for simple gates like API keys, maintenance mode, or rate limits.
Wrapping the whole call with an interceptor
Hooks run at a point in the pipeline. When you need code to run around everything that follows (for example try/finally, or withContext for an MDC or tracing context), use a pipeline interceptor and call proceed():
import io.ktor.server.application.*
fun Application.installInFlightCounter() {
val inFlight = java.util.concurrent.atomic.AtomicInteger()
intercept(ApplicationCallPipeline.Monitoring) {
inFlight.incrementAndGet()
try {
proceed() // runs the rest of the pipeline, including routing
} finally {
inFlight.decrementAndGet()
}
}
}
Built-in Ktor plugins
Most common middleware already ships with Ktor:
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.plugins.calllogging.*
import io.ktor.server.plugins.callid.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.defaultheaders.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.slf4j.event.Level
import java.util.UUID
fun Application.module() {
// Request ID: reuse incoming X-Request-Id or generate one, echo it back
install(CallId) {
retrieveFromHeader(HttpHeaders.XRequestId)
generate { UUID.randomUUID().toString() }
verify { it.isNotEmpty() }
replyToHeader(HttpHeaders.XRequestId)
}
// Access log; puts the call id into the logging MDC as "call-id"
install(CallLogging) {
level = Level.INFO
callIdMdc("call-id")
filter { call -> call.request.path().startsWith("/api") }
}
install(DefaultHeaders) {
header("X-Service", "orders")
}
install(CORS) {
allowHost("app.example.com", schemes = listOf("https"))
allowHeader(HttpHeaders.ContentType)
allowMethod(HttpMethod.Put)
allowMethod(HttpMethod.Delete)
}
// Exception -> response mapping
install(StatusPages) {
exception<IllegalArgumentException> { call, cause ->
call.respondText(cause.message ?: "Bad request", status = HttpStatusCode.BadRequest)
}
exception<Throwable> { call, cause ->
call.application.log.error("Unhandled error", cause)
call.respondText("Internal server error", status = HttpStatusCode.InternalServerError)
}
status(HttpStatusCode.NotFound) { call, _ ->
call.respondText("Nothing here", status = HttpStatusCode.NotFound)
}
}
// Our custom plugins
install(RequestTiming)
install(SecurityHeaders) { hsts = false }
routing {
get("/api/hello") {
call.respondText("Hello, request ${call.callId}")
}
get("/api/fail") {
throw IllegalArgumentException("id must be positive")
}
route("/admin") {
install(RequireApiKey) { validKeys = setOf("s3cret") }
get("/stats") { call.respondText("admin stats") }
}
}
}
fun main() {
embeddedServer(Netty, port = 8080, module = Application::module).start(wait = true)
}
Try it:
curl -i http://localhost:8080/api/hello
curl -i http://localhost:8080/api/fail
curl -i http://localhost:8080/admin/stats # 401
curl -i -H "X-API-Key: s3cret" http://localhost:8080/admin/stats
Testing middleware
Ktor's testApplication runs the full pipeline in memory, so plugins are exercised exactly as in production:
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlin.test.*
class MiddlewareTest {
@Test
fun `admin route requires api key`() = testApplication {
application { module() }
assertEquals(HttpStatusCode.Unauthorized, client.get("/admin/stats").status)
val ok = client.get("/admin/stats") { header("X-API-Key", "s3cret") }
assertEquals(HttpStatusCode.OK, ok.status)
assertEquals("admin stats", ok.bodyAsText())
}
@Test
fun `adds timing and request id headers`() = testApplication {
application { module() }
val resp = client.get("/api/hello")
assertNotNull(resp.headers["X-Response-Time"])
assertNotNull(resp.headers[HttpHeaders.XRequestId])
assertEquals("nosniff", resp.headers["X-Content-Type-Options"])
}
}
Best practices
- Be deliberate about order. Install error handling (
StatusPages) and request IDs early, so everything after them benefits. Plugins using the same hook run in installation order. - Scope narrowly. Use route-scoped plugins for concerns that apply only to some routes (admin auth, rate limits) instead of checking paths inside a global plugin.
- Do not block. Hooks are
suspendlambdas running on the server's coroutine dispatchers. Wrap blocking I/O inwithContext(Dispatchers.IO). - Pass data via
call.attributes, not global mutable state or thread-locals; a single request may hop between threads. - Keep middleware small and focused. One plugin per concern composes and tests better than one large "everything" plugin.
- Never log secrets. Access-log middleware should redact
Authorization,Cookieand API-key headers.