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.

Cookie

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

  1. install(Sessions) {
  2. cookie<SampleSession>("SAMPLE_SESSION")
  3. }

In the example above, session data will be passed to the client using the SAMPLE_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:

  1. install(Sessions) {
  2. cookie<SampleSession>("SAMPLE_SESSION") {
  3. cookie.path = "/orders"
  4. cookie.maxAgeInSeconds = 1000
  5. }
  6. }

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

  1. install(Sessions) {
  2. cookie<SampleSession>("SAMPLE_SESSION") {
  3. cookie.extensions["SameSite"] = "lax"
  4. }
  5. }

To learn more about available configurations settings, see CookieConfiguration.

Header

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

  1. install(Sessions) {
  2. header<SampleSession>("SAMPLE_SESSION")
  3. }

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