-
Notifications
You must be signed in to change notification settings - Fork 3
Sessions
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")
}
}
Before configuring a session, you need to create a data class for storing session data.
data class UserSession(val id: String, val count: Int)
val router = routing {
install(Sessions) {
session<UserSession>()
}
}
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))
// ...
}
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>()
// ...
}
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 {
// ...
}
}
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")
}