Sessions
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
plugin (previously known as feature), and set the session's content.
Add dependencies
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.
Install Sessions
Before installing a session, you need to create a data class for storing session data, for example:
Note that you can optionally inherit this class from Principal to use a session for authentication.
After creating the required data classes, you can install the Sessions
plugin 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 pass data between the server and client:
You can now set the session content, modify the session, or clear it.
Multiple sessions
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 data and settings:
You can store a user identifier on the server in a directory storage and pass user preferences to the client.
Note that session names should be unique.
Get and set session content
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:
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 clear
function: