Kotlin

Ktor Server — Middleware (Plugins)

admin by @admin ADMIN
5h ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Plugins wrap every request — logging, CORS, auth, rate limiting. Install with `install(Plugin) { config }` at the application level.
Kotlin
Raw
import io.ktor.server.engine.*
import io.ktor.server.netty.*
import io.ktor.server.application.*
import io.ktor.server.plugins.callloging.*
import io.ktor.server.plugins.cors.routing.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.http.*
import org.slf4j.event.Level

fun main() {
    embeddedServer(Netty, port = 8080) {
        // Log every incoming request with timing
        install(CallLogging) { level = Level.INFO }

        // CORS — allow your frontend origin
        install(CORS) {
            allowHost("localhost:3000")
            allowMethod(HttpMethod.Post)
            allowHeader(HttpHeaders.ContentType)
        }

        // Catch unhandled exceptions and turn them into JSON 500s
        install(StatusPages) {
            exception<Throwable> { call, cause ->
                call.respond(HttpStatusCode.InternalServerError,
                    mapOf("error" to (cause.message ?: "unknown")))
            }
        }

        routing {
            get("/") { call.respondText("ok") }
        }
    }.start(wait = true)
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.