Kest

Search

Search the documentation

HTTP

Cookies

Read and set the small pieces of data a browser sends back to you.

A cookie is a small value your server asks the browser to remember and send back on every later request to your site. They keep a visitor's theme, a language choice, or a session id.

@Controller("/prefs")
class PrefsController {
    @Get fun read(@Cookie("theme") theme: String?): String = theme ?: "light"                          // a request cookie, null if absent
 
    @Post fun save(@Query theme: String, ctx: HttpContext) {
        ctx.setCookie(ResponseCookie("theme", theme, maxAge = Duration.ofDays(365), httpOnly = false, secure = true, sameSite = "Lax"))
    }
}
Loading diagram…

ResponseCookie(name, value, maxAge, path = "/", domain, secure, httpOnly = true, sameSite = "Lax"). With @Response use res.cookie(ResponseCookie(...)). Several cookies in one response each stay a separate Set-Cookie header.

The flags that matter

FlagMeaningUse it
httpOnlyJavaScript on the page cannot read ityes for anything sensitive (a session id): a script injection cannot steal it. Default is on; turn it off only when your own script must read it
secureonly sent over HTTPSyes in production
sameSitewhen the browser sends it on cross-site requests: Lax (not on cross-site POSTs; default), Strict (never cross-site), None (always; needs secure)Lax, unless you need cross-site (then None + secure)
maxAgehow long it lives; without it, until the browser closesset it for "remember me" things
path, domainwhere it appliesthe defaults (/, this host) are usually right

Set it again with maxAge = Duration.ZERO (the same name, path and domain).

  • Not secrets or personal data in plain text: the user can read and change a cookie. Put an id in it and the data on the server (Session), or a signed token.
  • Not large data: browsers allow about 4 KB per cookie, and every request carries all of them.

Cookies that carry authentication need CSRF protection. For logins, prefer a session (the cookie holds only an id) or a Bearer token. Tracking cookies may need the visitor's consent under privacy laws: check your obligations.

Read more