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"))
}
}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
| Flag | Meaning | Use it |
|---|---|---|
httpOnly | JavaScript on the page cannot read it | yes 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 |
secure | only sent over HTTPS | yes in production |
sameSite | when 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) |
maxAge | how long it lives; without it, until the browser closes | set it for "remember me" things |
path, domain | where it applies | the defaults (/, this host) are usually right |
Deleting a cookie
Set it again with maxAge = Duration.ZERO (the same name, path and domain).
What not to put in a cookie
- 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.