Sessions provide a mechanism to persist data between different HTTP requests. Typical use cases include storing a logged-in user's ID, the contents of a shopping basket, or keeping user preferences on the client. In Ktor, you can implement sessions by using cookies or custom headers, choose whether to store session data on the server or pass it to the client, sign and encrypt session data, and more.
In this topic, we'll look at how to configure sessions, install the
Sessions feature, and set the session's content.
To enable support for sessions, you need to include the
ktor-server-sessions artifact in the build script:
Session configuration overview
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.
Where to store the session payload: 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.
How to serialize session data: using a default format, JSON, or a custom engine.
Where to store the payload on the server: in the server memory or in a folder. You can also implement a custom storage for keeping session data.
How to transform the payload: you can sign or encrypt data sent to the client for security reasons.
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
header function depending on how you want to pass data between the server and client:
You can now set the session content, modify the session, or clear it.
If you need several sessions in your application, you need to create a separate data class for each session. For example, you can create separate data classes for storing a user login and settings:
You can store a username on the server in a directory storage and pass user preferences to the client.
Note that session names should be unique.
Set session content
To get the session content, you can call get receiving one of the registered session types as type parameter:
To modify a session, for example, to increment a counter, you need to call the
copy method of the data class:
When you need to clear a session for any reason (for example, when a user logs out), call the