Sessions

suggest change

HTTP is a stateless protocol. To preserve user context across multiple requests—such as shopping carts, authenticated user profiles, or multi-step wizard state—web applications rely on sessions.

In Kotlin backend frameworks like Ktor or Spring Boot, sessions can be persisted client-side (inside signed and encrypted cookies) or server-side (in memory, Redis, or a relational database, referenced by a session ID cookie).


Sessions in Ktor

Ktor provides built-in support for sessions via the ktor-server-sessions plugin.

Add the dependency to build.gradle.kts, together with the kotlinx.serialization plugin used to serialize session data:

plugins {
    kotlin("plugin.serialization") version "2.4.21"
}

dependencies {
    implementation("io.ktor:ktor-server-sessions:3.6.0")
}

Modeling Session Data with Data Classes

Ktor serializes sessions directly into Kotlin data class representations marked with @Serializable:

import kotlinx.serialization.Serializable

@Serializable
data class UserSession(
    val userId: String,
    val roles: List<String> = emptyList(),
    val cartCount: Int = 0
)

In client-side sessions, the serialized session payload is stored directly in the user's browser cookie. To ensure the user cannot tamper with or inspect the data, Ktor provides HMAC signature and encryption transformers:

import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import io.ktor.server.sessions.*

fun Application.configureClientSessions() {
    // in production, load secret keys from environment variables
    val signKey = "6819b57a326945c1968f45236589a1f3".hexToByteArray()    // HMAC key
    val encryptKey = "ba816d24a569f41b9015c71a3962e8d0".hexToByteArray() // AES key: 16, 24 or 32 bytes

    install(Sessions) {
        cookie<UserSession>("USER_SESSION") {
            cookie.path = "/"
            cookie.maxAgeInSeconds = 3600 * 24 // 1 day
            cookie.httpOnly = true             // Prevents XSS script access
            cookie.secure = true               // Sent only over HTTPS
            cookie.extensions["SameSite"] = "Lax"

            // Sign and encrypt cookie payload
            transform(SessionTransportTransformerEncrypt(encryptKey, signKey))
        }
    }

    routing {
        // Read or create session
        get("/cart") {
            val session = call.sessions.get<UserSession>() ?: UserSession(userId = "guest")
            call.respondText("Cart count: ${session.cartCount}")
        }

        // Update session
        post("/cart/add") {
            val current = call.sessions.get<UserSession>() ?: UserSession(userId = "guest")
            val updated = current.copy(cartCount = current.cartCount + 1)
            call.sessions.set(updated)
            call.respondText("Item added! Total: ${updated.cartCount}")
        }

        // Invalidate / clear session (Logout)
        post("/logout") {
            call.sessions.clear<UserSession>()
            call.respondText("Logged out successfully.")
        }
    }
}

Server-Side Sessions

When session payloads are large or contain sensitive internal identifiers, server-side storage is preferred. The client receives an opaque session identifier cookie, and the state is stored on the server.

In-Memory Server Sessions (Development)

import io.ktor.server.application.*
import io.ktor.server.sessions.*

fun Application.configureInMemoryServerSessions() {
    install(Sessions) {
        cookie<UserSession>("SESSION_ID", SessionStorageMemory()) {
            cookie.path = "/"
            cookie.httpOnly = true
            cookie.secure = true
        }
    }
}

Distributed Server Storage (Custom SessionStorage)

For clustered or multi-instance deployments, implement Ktor's SessionStorage interface backed by a cache (such as Redis):

import io.ktor.server.sessions.*

class RedisSessionStorage(private val redisClient: FakeRedisClient) : SessionStorage {

    override suspend fun write(id: String, value: String) {
        redisClient.set("session:$id", value, ttlSeconds = 3600)
    }

    override suspend fun read(id: String): String {
        return redisClient.get("session:$id") ?: throw NoSuchElementException("Session $id not found")
    }

    override suspend fun invalidate(id: String) {
        redisClient.del("session:$id")
    }
}

// Dummy client representation for illustration
class FakeRedisClient {
    private val store = mutableMapOf<String, String>()
    fun set(key: String, value: String, ttlSeconds: Int) { store[key] = value }
    fun get(key: String): String? = store[key]
    fun del(key: String) { store.remove(key) }
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents