Ktor 1.6.7 Help

Cookie/Header

Sessions allow you to choose between two ways of transferring data within HTTP requests: cookies or custom headers. Cookies suit better for plain HTML applications while custom headers are intended for APIs (for both Fetch API and requesting headers from the server).

Configure Cookie/Header

Sessions.Configuration provides the cookie and header methods for selecting how to transfer session data. For both ways, you can choose whether to pass the entire session data between the client and server or only the session ID and store data on the server. If you pass data to the client, you need to apply transforms to encrypt or authenticate sessions.

To pass session data using cookies, call the cookie method with the specified name and data class inside the install(Sessions) block:

install(Sessions) { cookie<UserSession>("user_session") }

In the example above, session data will be passed to the client using the user_session attribute added to the Set-Cookie header. You can configure other cookie attributes by passing them inside the cookie block. For example, the code snippet below shows how to specify a cookie's path and expiration time:

install(Sessions) { cookie<UserSession>("user_session") { cookie.path = "/" cookie.maxAgeInSeconds = 10 } }

If the required attribute is not exposed explicitly, use the extensions property. For example, you can pass the SameSite attribute in the following way:

install(Sessions) { cookie<UserSession>("user_session") { cookie.extensions["SameSite"] = "lax" } }

To learn more about available configurations settings, see CookieConfiguration.

To pass session data using a custom header, call the header method with the specified name and data class inside the install(Sessions) block:

install(Sessions) { header<UserSession>("user_session") }

In the example above, session data will be passed to the client using the user_session header.

Last modified: 08 June 2021