Sessions

    In this topic, we’ll look at how to configure sessions, install the feature, and set the session’s content.

    You can configure sessions in the following ways:

    • How to pass data between the server and client: using cookies or custom headers. Cookies suit better for plain HTML applications while custom headers are intended for APIs.

    • : on the client or server. You can pass the serialized session’s data to the client using a cookie/header value or store the payload on the server and pass only a session ID.

    • : using a default format, JSON, or a custom engine.

    Before installing a session, you need to create a data class for storing session data, for example:

    You need to create several data classes if you are going to use several sessions.

    After creating the required data classes, you can install the Sessions feature by passing it to the install function in the application initialization code. Inside the install block, call the cookie or header function depending on how you want to :

    1. import io.ktor.features.*
    2. import io.ktor.sessions.*
    3. fun Application.module() {
    4. install(Sessions) {
    5. cookie<LoginSession>("LOGIN_SESSION")
    6. }
    7. }

    You can now set the session content, modify the session, or clear it.

    You can store a username on the server in a and pass user preferences to the client.

    1. cookie<LoginSession>("LOGIN_SESSION", directorySessionStorage(File(".sessions"), cached = true))
    2. }

    Note that session names should be unique.

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

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

    1. routing {
    2. get("/") {
    3. val loginSession: LoginSession? = call.sessions.get<LoginSession>()
    4. }
    5. }

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