Skip to content

Sessions

Thiago Santos edited this page Aug 14, 2024 · 1 revision

The Sessions plugin provides a mechanism to persist data between different routes. Typical use cases include storing a logged-in user's ID, the contents of a shopping basket, or keeping user preferences on Routing lifecycle. In memory session is available only.

sourceSets {
    commonMain.dependencies {
        implementation("dev.programadorthi.routing:sessions:$version")
    }
}

Session configuration

Create a data class

Before configuring a session, you need to create a data class for storing session data.

data class UserSession(val id: String, val count: Int)

Setup the plugin

val router = routing {
    install(Sessions) {
        session<UserSession>()
    }
}

Store a session

To set the session content for a specific route, use the call.sessions property. The set method allows you to create a new session instance:

router.handle(path = "/home") {
    call.sessions.set(UserSession(id = "123abc", count = 0))
    // ...
}

Get a session

To get the session content, you can call get receiving one of the registered session types as type parameter:

router.handle(path = "/profile") {
    val userSession = call.sessions.get<UserSession>()
    // ...
}

Modify a session

To modify a session, for example, to increment a counter, you need to call the copy method of the data class:

router.handle(path = "/profile") {
    val userSession = call.sessions.get<UserSession>()
    if (userSession != null) {
        call.sessions.set(userSession.copy(count = userSession.count + 1))
        // ...
    } else {
        // ...
    }
}

Clear a session

When you need to clear a session for any reason (for example, when a user logs out), call the clear function:

router.handle(path = "/logout") {
    call.sessions.clear<UserSession>()
    call.redirectToPath(path = "/login")
}