Cookies
suggest changeA cookie is a small name/value pair that a server asks the client to store and send back with later requests. Cookies are how a stateless protocol like HTTP remembers things: who is logged in, which language the user picked, what's in a cart.
This article covers:
- how cookies travel in
Set-CookieandCookieheaders - the cookie attributes and what they're for
- writing and reading cookies on a server with only the JDK
- a cookie jar for
java.net.http.HttpClient - deleting cookies
- signing cookies so users can't tamper with them
- cookies in Ktor, on the server and in the client
Session management built on top of cookies is covered in Sessions.
How cookies work
The server sends a Set-Cookie response header for each cookie:
HTTP/1.1 200 OK
Set-Cookie: session=f3a9c2; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; Path=/
The client stores them and sends the matching ones back in a single Cookie request header:
GET /account HTTP/1.1
Cookie: session=f3a9c2; theme=dark
The two headers have different formats. Set-Cookie carries one cookie plus its attributes. Cookie carries only name=value pairs separated by ; . The client never sends attributes back, so the server can't tell when a cookie expires or which path it was set for.
Attributes in Set-Cookie:
| Attribute | Meaning |
|---|---|
Max-Age=N |
delete after N seconds; 0 deletes now |
Expires=<date> |
delete at this date (older form, Max-Age wins if both are set) |
Path=/p |
send only for URLs under /p |
Domain=example.com |
send to this domain and its subdomains; omit it to limit the cookie to the exact host |
Secure |
send only over HTTPS |
HttpOnly |
JavaScript can't read it through document.cookie |
SameSite=Strict|Lax|None |
whether to send it on cross-site requests; browsers default to Lax |
A cookie with neither Max-Age nor Expires is a session cookie: the browser drops it when it closes.
Browsers limit each cookie to about 4 KB and each domain to a few dozen cookies. Every matching cookie goes out with every request, images and scripts included, so keep them small.
Building Set-Cookie headers
The JDK has java.net.HttpCookie, but it's not a good fit for writing Set-Cookie headers (more on that below). A small class is enough:
import java.net.URLDecoder
import java.net.URLEncoder
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import kotlin.text.Charsets.UTF_8
enum class SameSite { Strict, Lax, None }
data class SetCookie(
val name: String,
val value: String,
val path: String? = "/",
val domain: String? = null,
val maxAge: Long? = null,
val expires: ZonedDateTime? = null,
val secure: Boolean = false,
val httpOnly: Boolean = false,
val sameSite: SameSite? = null,
) {
init {
require(name.isNotEmpty() && name.none { it in "()<>@,;:\\\"/[]?={} \t" || it.code < 33 || it.code > 126 }) {
"invalid cookie name: '$name'"
}
}
fun toHeader(): String = buildString {
append(name).append('=').append(URLEncoder.encode(value, UTF_8))
path?.let { append("; Path=").append(it) }
domain?.let { append("; Domain=").append(it) }
maxAge?.let { append("; Max-Age=").append(it) }
expires?.let {
append("; Expires=")
append(DateTimeFormatter.RFC_1123_DATE_TIME.format(it.withZoneSameInstant(ZoneOffset.UTC)))
}
if (secure) append("; Secure")
if (httpOnly) append("; HttpOnly")
sameSite?.let { append("; SameSite=").append(it.name) }
}
}
// Parses a request header like "a=1; b=2" into a map
fun parseCookieHeader(header: String?): Map<String, String> {
if (header.isNullOrBlank()) return emptyMap()
return header.split(';')
.mapNotNull { part ->
val i = part.indexOf('=')
if (i <= 0) null
else part.substring(0, i).trim() to
URLDecoder.decode(part.substring(i + 1).trim().removeSurrounding("\""), UTF_8)
}
.toMap()
}
fun main() {
val session = SetCookie(
name = "session",
value = "f3a9c2",
maxAge = 3600,
secure = true,
httpOnly = true,
sameSite = SameSite.Lax,
)
println(session.toHeader())
val prefs = SetCookie(
name = "prefs",
value = "theme=dark; lang=pl",
expires = ZonedDateTime.of(2027, 1, 31, 12, 0, 0, 0, ZoneOffset.UTC),
)
println(prefs.toHeader())
val deleted = SetCookie(name = "session", value = "", maxAge = 0)
println(deleted.toHeader())
val parsed = parseCookieHeader("session=f3a9c2; prefs=theme%3Ddark%3B+lang%3Dpl; flag")
println(parsed)
try {
SetCookie(name = "my cookie", value = "x")
} catch (e: IllegalArgumentException) {
println("error: ${e.message}")
}
}
Output:
session=f3a9c2; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax
prefs=theme%3Ddark%3B+lang%3Dpl; Path=/; Expires=Sun, 31 Jan 2027 12:00:00 GMT
session=; Path=/; Max-Age=0
{session=f3a9c2, prefs=theme=dark; lang=pl}
error: invalid cookie name: 'my cookie'
Things to note:
- Cookie names are restricted to printable ASCII without separators.
initrejects anything else, because a bad name would corrupt the header. - Values can't contain
;,,, spaces, or quotes. Encoding the value withURLEncoderand decoding withURLDecoderis the usual way around it. Base64url is another option. Expiresuses the HTTP date format, always in GMT.DateTimeFormatter.RFC_1123_DATE_TIMEproduces it.parseCookieHeader()handles theCookierequest header. Parts without=are skipped instead of failing, since browsers and proxies send odd things.SameSite=Noneonly works together withSecure. Browsers reject the cookie otherwise.
Parsing Set-Cookie with HttpCookie
On the client side you sometimes need to parse a Set-Cookie header yourself. HttpCookie.parse() does that:
import java.net.HttpCookie
fun main() {
val header = "session=abc123; Path=/; Domain=example.com; Max-Age=3600; Secure; HttpOnly; SameSite=Lax"
val cookies: List<HttpCookie> = HttpCookie.parse(header)
val c = cookies.single()
println("name: ${c.name}")
println("value: ${c.value}")
println("path: ${c.path}")
println("domain: ${c.domain}")
println("maxAge: ${c.maxAge}")
println("secure: ${c.secure}")
println("httpOnly: ${c.isHttpOnly}")
println("expired: ${c.hasExpired()}")
println("version: ${c.version}")
println("toString: $c")
val expires = HttpCookie.parse("theme=dark; Expires=Wed, 21 Oct 2037 07:28:00 GMT; Path=/").single()
println("expires-based maxAge > 0: ${expires.maxAge > 0}")
val created = HttpCookie("lang", "en").apply {
path = "/"
maxAge = 86400
isHttpOnly = true
}
println("created: $created")
println(HttpCookie.domainMatches(".example.com", "www.example.com"))
}
Output:
name: session
value: abc123
path: /
domain: example.com
maxAge: 3600
secure: true
httpOnly: true
expired: false
version: 1
toString: session="abc123";$Path="/";$Domain="example.com"
expires-based maxAge > 0: true
created: lang="en";$Path="/"
true
HttpCookie has some quirks:
parse()expects aSet-Cookieheader. Don't use it for theCookierequest header: it readsa=1; b=2as one cookieawith an unknown attributeb.- It has no property for
SameSite. The attribute is accepted and ignored. Expiresis converted tomaxAgerelative to the moment of parsing.toString()produces the obsolete RFC 2965 format ($Path, quoted values). Never use it to write aSet-Cookieheader.
HttpCookie is mainly useful as the element type of CookieStore, which is the cookie jar used by CookieManager in the next section.
A server and client with the JDK only
com.sun.net.httpserver.HttpServer is built into the JDK. Reading a cookie means parsing the Cookie header, writing one means adding a Set-Cookie header. The client uses java.net.http.HttpClient with a CookieManager, which stores cookies from responses and sends them with the next requests, like a browser would.
Compile this together with SetCookie and parseCookieHeader() from above:
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpServer
import java.net.CookieManager
import java.net.CookiePolicy
import java.net.InetSocketAddress
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
fun HttpExchange.cookies(): Map<String, String> =
parseCookieHeader(requestHeaders.getFirst("Cookie"))
fun HttpExchange.setCookie(cookie: SetCookie) {
// add(), not set(): every cookie needs its own Set-Cookie header
responseHeaders.add("Set-Cookie", cookie.toHeader())
}
fun HttpExchange.reply(text: String) {
val bytes = text.toByteArray()
sendResponseHeaders(200, bytes.size.toLong())
responseBody.use { it.write(bytes) }
}
fun startServer(): HttpServer {
val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
server.createContext("/visit") { ex ->
val visits = (ex.cookies()["visits"]?.toIntOrNull() ?: 0) + 1
ex.setCookie(SetCookie("visits", visits.toString(), maxAge = 3600, httpOnly = true, sameSite = SameSite.Lax))
ex.reply("visit #$visits")
}
server.createContext("/theme") { ex ->
val theme = ex.requestURI.query?.removePrefix("set=")
if (theme != null) {
ex.setCookie(SetCookie("theme", theme, maxAge = 365L * 24 * 3600, sameSite = SameSite.Lax))
ex.reply("theme set to $theme")
} else {
ex.reply("theme is ${ex.cookies()["theme"] ?: "light (default)"}")
}
}
server.createContext("/reset") { ex ->
// to delete a cookie, send it again with Max-Age=0 and the same Path and Domain
ex.setCookie(SetCookie("visits", "", maxAge = 0))
ex.setCookie(SetCookie("theme", "", maxAge = 0))
ex.reply("cookies cleared")
}
server.start()
return server
}
fun main() {
val server = startServer()
val base = "http://127.0.0.1:${server.address.port}"
val cookieManager = CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)
val client = HttpClient.newBuilder().cookieHandler(cookieManager).build()
fun get(path: String) {
val req = HttpRequest.newBuilder(URI("$base$path")).build()
val resp = client.send(req, HttpResponse.BodyHandlers.ofString())
println("GET %-16s -> %s".format(path, resp.body()))
resp.headers().allValues("Set-Cookie").forEach { println(" Set-Cookie: $it") }
}
get("/visit")
get("/visit")
get("/theme?set=dark")
get("/theme")
println("cookie jar: ${cookieManager.cookieStore.cookies.map { "${it.name}=${it.value}" }}")
get("/reset")
println("cookie jar: ${cookieManager.cookieStore.cookies}")
get("/visit")
// without a CookieHandler, set the Cookie header yourself
val plain = HttpClient.newHttpClient()
val req = HttpRequest.newBuilder(URI("$base/theme")).header("Cookie", "theme=blue").build()
println("manual: " + plain.send(req, HttpResponse.BodyHandlers.ofString()).body())
server.stop(0)
}
Output:
GET /visit -> visit #1
Set-Cookie: visits=1; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax
GET /visit -> visit #2
Set-Cookie: visits=2; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax
GET /theme?set=dark -> theme set to dark
Set-Cookie: theme=dark; Path=/; Max-Age=31536000; SameSite=Lax
GET /theme -> theme is dark
cookie jar: [visits=2, theme=dark]
GET /reset -> cookies cleared
Set-Cookie: visits=; Path=/; Max-Age=0
Set-Cookie: theme=; Path=/; Max-Age=0
cookie jar: []
GET /visit -> visit #1
Set-Cookie: visits=1; Path=/; Max-Age=3600; HttpOnly; SameSite=Lax
manual: theme is blue
Things to note:
- Use
responseHeaders.add(), notset(), forSet-Cookie.set()replaces earlier values, so only the last cookie would reach the client. You must not merge multiple cookies into one header with commas either, becauseExpiresdates contain commas. - To delete a cookie, send it again with
Max-Age=0(or anExpiresdate in the past).PathandDomainmust match the original exactly, otherwise the client treats it as a different cookie and keeps the old one. CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)uses an in-memory store and only accepts cookies whoseDomainmatches the server that sent them.ACCEPT_ALLandACCEPT_NONEare the other policies.HttpClient.newHttpClient()has no cookie handler, so it ignoresSet-Cookie. You can then set theCookieheader on each request yourself.- The visit counter is stored in plain text. Anyone can edit it in the browser's developer tools and send
visits=1000. The next section fixes that.
Signed cookies
Never trust a cookie value. The client can change it, delete it, or send cookies you never set. If a cookie must not be modified, add a signature computed with a secret key that only the server knows. HMAC-SHA256 is the standard choice:
import java.security.MessageDigest
import java.time.Instant
import java.util.Base64
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
class CookieSigner(secret: ByteArray) {
private val key = SecretKeySpec(secret, "HmacSHA256")
private val b64 = Base64.getUrlEncoder().withoutPadding()
private fun mac(data: String): String =
b64.encodeToString(Mac.getInstance("HmacSHA256").apply { init(key) }.doFinal(data.toByteArray()))
// base64(value).expiresEpochSeconds.signature
fun sign(value: String, ttlSeconds: Long, now: Instant = Instant.now()): String {
val payload = b64.encodeToString(value.toByteArray()) + "." + (now.epochSecond + ttlSeconds)
return payload + "." + mac(payload)
}
fun verify(cookie: String, now: Instant = Instant.now()): String? {
val parts = cookie.split('.')
if (parts.size != 3) return null
val payload = parts[0] + "." + parts[1]
val expected = mac(payload).toByteArray()
// constant-time comparison so timing doesn't leak how many bytes matched
if (!MessageDigest.isEqual(expected, parts[2].toByteArray())) return null
val expiresAt = parts[1].toLongOrNull() ?: return null
if (now.epochSecond >= expiresAt) return null
return String(Base64.getUrlDecoder().decode(parts[0]))
}
}
fun main() {
// in production load the secret from configuration, at least 32 random bytes
val signer = CookieSigner("0123456789abcdef0123456789abcdef".toByteArray())
val now = Instant.parse("2026-10-17T12:00:00Z")
val cookie = signer.sign("user:42", ttlSeconds = 3600, now = now)
println("cookie value: $cookie")
println("verified: ${signer.verify(cookie, now)}")
val forged = cookie.replaceFirst(cookie.substringBefore('.'),
Base64.getUrlEncoder().withoutPadding().encodeToString("user:1".toByteArray()))
println("forged: ${signer.verify(forged, now)}")
println("expired: ${signer.verify(cookie, now.plusSeconds(7200))}")
println("garbage: ${signer.verify("hello", now)}")
}
Output:
cookie value: dXNlcjo0Mg.1792242000.HbiPuncBXPppcn5pMv2T8ZPrwJDYlB7wshsO4Q8DMwU
verified: user:42
forged: null
expired: null
garbage: null
Things to note:
- The cookie contains the value, an expiry time, and the HMAC of both. Changing any part invalidates the signature.
- The expiry is inside the signed payload.
Max-Ageonly tells the browser when to drop the cookie. An attacker can keep a copy and replay it later, so the server must check the expiry itself. MessageDigest.isEqual()compares in constant time.==stops at the first different byte, which can leak information about the correct signature through timing.- Signing is not encryption.
dXNlcjo0Mgis just Base64 foruser:42, and anyone can decode it. Don't put secrets in cookies, or encrypt them with AES-GCM as well (see Cryptography). - Rotating the secret logs out everyone. To rotate without that, verify against a list of keys (new first, old second) and sign only with the new one.
This is the same idea as Ktor's SessionTransportTransformerMessageAuthentication and as a JWT stored in a cookie.
Cookies in Ktor
Ktor has cookie support built into the core, no plugin required:
val ktorVersion = "3.6.0"
dependencies {
implementation("io.ktor:ktor-server-netty:$ktorVersion")
implementation("io.ktor:ktor-client-cio:$ktorVersion")
implementation("org.slf4j:slf4j-nop:2.0.17")
}
The server sets cookies with call.response.cookies.append() and reads them with call.request.cookies[name]. On the client, the HttpCookies plugin is the cookie jar:
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.cookies.HttpCookies
import io.ktor.client.plugins.cookies.cookies
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.statement.bodyAsText
import io.ktor.http.Cookie
import io.ktor.http.setCookie
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.routing
import io.ktor.util.date.GMTDate
import kotlinx.coroutines.runBlocking
fun main() {
val server = embeddedServer(Netty, host = "127.0.0.1", port = 0) {
routing {
post("/login") {
call.response.cookies.append(
Cookie(
name = "user",
value = "ann smith",
maxAge = 3600,
path = "/",
secure = false, // true in production (HTTPS)
httpOnly = true,
extensions = mapOf("SameSite" to "Lax"),
)
)
call.response.cookies.append("theme", "dark", path = "/")
call.respondText("logged in")
}
get("/me") {
val user = call.request.cookies["user"]
val theme = call.request.cookies["theme"] ?: "light"
call.respondText("user=$user theme=$theme all=${call.request.cookies.rawCookies}")
}
post("/logout") {
// delete: same name and path, expiry in the past
call.response.cookies.append(Cookie("user", "", maxAge = 0, expires = GMTDate.START, path = "/"))
call.respondText("logged out")
}
}
}.start(wait = false)
runBlocking {
val port = server.engine.resolvedConnectors().first().port
val base = "http://127.0.0.1:$port"
HttpClient(CIO) {
install(HttpCookies) // in-memory cookie jar (AcceptAllCookiesStorage)
}.use { client ->
val login = client.post("$base/login")
println(login.bodyAsText())
login.headers.getAll("Set-Cookie")?.forEach { println(" Set-Cookie: $it") }
println(" parsed: " + login.setCookie().map { "${it.name}=${it.value} maxAge=${it.maxAge} httpOnly=${it.httpOnly}" })
println(client.get("$base/me").bodyAsText())
println("jar: " + client.cookies(base).map { "${it.name}=${it.value}" })
val logout = client.post("$base/logout")
println(logout.bodyAsText())
logout.headers.getAll("Set-Cookie")?.forEach { println(" Set-Cookie: $it") }
println(client.get("$base/me").bodyAsText())
println("jar: " + client.cookies(base).map { "${it.name}=${it.value}" })
}
}
server.stop(100, 500)
}
Output:
logged in
Set-Cookie: user=ann+smith; Max-Age=3600; Path=/; HttpOnly; SameSite=Lax; $x-enc=URI_ENCODING
Set-Cookie: theme=dark; Path=/; $x-enc=URI_ENCODING
parsed: [user=ann smith maxAge=3600 httpOnly=true, theme=dark maxAge=null httpOnly=false]
user=ann smith theme=dark all={user=ann+smith, theme=dark}
jar: [user=ann smith, theme=dark]
logged out
Set-Cookie: user=; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/; $x-enc=URI_ENCODING
user=null theme=dark all={theme=dark}
jar: [theme=dark]
Things to note:
Cookieencodes the value withCookieEncoding.URI_ENCODINGby default, andcall.request.cookies["user"]decodes it with the same encoding.rawCookiesgives you the values as sent.SameSitehas no dedicated parameter. Pass it throughextensions.- Ktor appends
$x-enc=URI_ENCODINGto everySet-Cookieheader it writes. Browsers ignore unknown attributes, so it's harmless. port = 0picks a free port.resolvedConnectors()tells you which one.appendExpired()is deprecated, so delete a cookie by appending it withmaxAge = 0andexpires = GMTDate.START.response.setCookie()parses allSet-Cookieheaders of a client response intoCookieobjects.install(HttpCookies)usesAcceptAllCookiesStorage, an in-memory jar that respectsMax-Age,Expires,DomainandPath.client.cookies(url)lists the cookies that would be sent to that URL.
For cookies the client should always send, such as a session token read from configuration, use ConstantCookiesStorage. Without the plugin, add cookies per request with cookie():
import io.ktor.client.HttpClient
import io.ktor.client.engine.cio.CIO
import io.ktor.client.plugins.cookies.ConstantCookiesStorage
import io.ktor.client.plugins.cookies.HttpCookies
import io.ktor.client.request.cookie
import io.ktor.client.request.get
import io.ktor.client.statement.bodyAsText
import io.ktor.http.Cookie
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.request.header
import io.ktor.server.response.respondText
import io.ktor.server.routing.get
import io.ktor.server.routing.routing
import kotlinx.coroutines.runBlocking
fun main() {
val server = embeddedServer(Netty, host = "127.0.0.1", port = 0) {
routing {
get("/echo") { call.respondText("Cookie: ${call.request.header("Cookie")}") }
}
}.start(wait = false)
runBlocking {
val base = "http://127.0.0.1:${server.engine.resolvedConnectors().first().port}"
// a fixed set of cookies sent with every request, e.g. an API token from config
HttpClient(CIO) {
install(HttpCookies) {
storage = ConstantCookiesStorage(Cookie("api_session", "s3cr3t", domain = "127.0.0.1"))
}
}.use { client ->
println(client.get("$base/echo").bodyAsText())
}
// without the plugin: set cookies per request
HttpClient(CIO).use { client ->
val body = client.get("$base/echo") {
cookie("debug", "1")
cookie("lang", "en")
}.bodyAsText()
println(body)
}
}
server.stop(100, 500)
}
Output:
Cookie: api_session=s3cr3t
Cookie: debug=1; lang=en
With HttpCookies installed, the plugin writes the Cookie header from its storage, and cookies added with cookie() on a single request are lost. Use one approach per client, not both.
To keep cookies across restarts, implement the CookiesStorage interface (get, addCookie, close) on top of a file or a database.
Security checklist
HttpOnlyon every cookie that JavaScript doesn't need, and always on session cookies. An XSS bug then can't steal the session.Secureon everything in production. Without it the cookie travels in plain text over any accidentalhttp://request. See TLS and HTTPS.SameSite=Lax(orStrict) protects against most CSRF attacks. UseNone; Secureonly for cookies that must be sent cross-site, and read CORS for the rest of the setup.- Cookie prefixes: browsers accept a cookie named
__Host-sessiononly if it hasSecureandPath=/and noDomain. Subdomains or anhttp://page can't overwrite it.__Secure-requires onlySecure. - Don't set
Domainunless subdomains really need the cookie. Without it the cookie stays on the exact host. - Store an ID, not data: keep the real state on the server and put a long random ID (
SecureRandom, 32 bytes) or a signed value in the cookie. - Never log
CookieorSet-Cookieheaders: they contain credentials. See HTTP headers.
Summary
| Task | JDK | Ktor |
|---|---|---|
| Set a cookie (server) | responseHeaders.add("Set-Cookie", ...) |
call.response.cookies.append(Cookie(...)) |
| Read a cookie (server) | parse requestHeaders.getFirst("Cookie") |
call.request.cookies["name"] |
| Delete a cookie | same name, path and domain with Max-Age=0 |
append(Cookie(name, "", maxAge = 0, expires = GMTDate.START)) |
| Cookie jar (client) | HttpClient.newBuilder().cookieHandler(CookieManager()) |
install(HttpCookies) |
Parse Set-Cookie (client) |
HttpCookie.parse(header) |
response.setCookie() |
| Send a cookie once (client) | .header("Cookie", "a=1") |
cookie("a", "1") |
| Tamper-proof value | HMAC-SHA256 with javax.crypto.Mac |
SessionTransportTransformerMessageAuthentication |