0
# Cookie Management
1
2
HTTP cookie creation, parsing, and rendering with encoding support, security options, and both client and server-side cookie handling.
3
4
## Capabilities
5
6
### Cookie Data Class
7
8
Serializable cookie representation with comprehensive attributes and security options.
9
10
```kotlin { .api }
11
/**
12
* HTTP cookie representation
13
*/
14
data class Cookie(
15
val name: String,
16
val value: String,
17
val encoding: CookieEncoding = CookieEncoding.RAW,
18
val maxAgeInt: Int? = null,
19
val expires: GMTDate? = null,
20
val domain: String? = null,
21
val path: String? = null,
22
val secure: Boolean = false,
23
val httpOnly: Boolean = false,
24
val extensions: Map<String, String> = emptyMap()
25
) : Serializable {
26
27
companion object {
28
fun serializer(): KSerializer<Cookie>
29
}
30
}
31
```
32
33
### Cookie Encoding
34
35
Encoding strategies for cookie values to handle special characters and security.
36
37
```kotlin { .api }
38
/**
39
* Cookie value encoding strategies
40
*/
41
enum class CookieEncoding {
42
/**
43
* No encoding (raw value)
44
*/
45
RAW,
46
47
/**
48
* Double-quote the value
49
*/
50
DQUOTES,
51
52
/**
53
* Base64 encode the value
54
*/
55
BASE64_ENCODING,
56
57
/**
58
* URI encode the value
59
*/
60
URI_ENCODING
61
}
62
```
63
64
### Cookie Rendering
65
66
Functions for rendering cookies in HTTP headers.
67
68
```kotlin { .api }
69
/**
70
* Render Set-Cookie header value
71
* @param cookie cookie to render
72
* @return Set-Cookie header value
73
*/
74
fun renderSetCookieHeader(cookie: Cookie): String
75
76
/**
77
* Render Set-Cookie header with individual parameters
78
* @param name cookie name
79
* @param value cookie value
80
* @param encoding value encoding strategy
81
* @param maxAge max age in seconds
82
* @param expires expiration date
83
* @param domain cookie domain
84
* @param path cookie path
85
* @param secure secure flag
86
* @param httpOnly HTTP-only flag
87
* @param extensions additional attributes
88
* @param includeEncoding whether to include encoding info
89
* @return Set-Cookie header value
90
*/
91
fun renderSetCookieHeader(
92
name: String,
93
value: String,
94
encoding: CookieEncoding = CookieEncoding.RAW,
95
maxAge: Int? = null,
96
expires: GMTDate? = null,
97
domain: String? = null,
98
path: String? = null,
99
secure: Boolean = false,
100
httpOnly: Boolean = false,
101
extensions: Map<String, String> = emptyMap(),
102
includeEncoding: Boolean = true
103
): String
104
105
/**
106
* Render Cookie header value (client-side)
107
* @param cookie cookie to render
108
* @return Cookie header value
109
*/
110
fun renderCookieHeader(cookie: Cookie): String
111
```
112
113
### Cookie Parsing
114
115
Functions for parsing cookies from HTTP headers.
116
117
```kotlin { .api }
118
/**
119
* Parse Set-Cookie header value (server-side)
120
* @param headerValue Set-Cookie header value
121
* @return Cookie instance
122
*/
123
fun parseServerSetCookieHeader(headerValue: String): Cookie
124
125
/**
126
* Parse Cookie header value (client-side)
127
* @param headerValue Cookie header value
128
* @param decodeValues whether to decode values
129
* @return Map of cookie names to values
130
*/
131
fun parseClientCookiesHeader(
132
headerValue: String,
133
decodeValues: Boolean = true
134
): Map<String, String>
135
```
136
137
### Cookie Value Encoding/Decoding
138
139
Low-level functions for encoding and decoding cookie values.
140
141
```kotlin { .api }
142
/**
143
* Encode cookie value according to encoding strategy
144
* @param value value to encode
145
* @param encoding encoding strategy
146
* @return encoded value
147
*/
148
fun encodeCookieValue(value: String, encoding: CookieEncoding): String
149
150
/**
151
* Decode cookie value according to encoding strategy
152
* @param value encoded value
153
* @param encoding encoding strategy used
154
* @return decoded value
155
*/
156
fun decodeCookieValue(value: String, encoding: CookieEncoding): String
157
```
158
159
### Date Utilities for Cookies
160
161
Date formatting and parsing specific to cookie expiration handling.
162
163
```kotlin { .api }
164
/**
165
* Convert cookie date string to GMTDate
166
* @param dateString cookie date string
167
* @return GMTDate instance
168
*/
169
fun fromCookieToGmtDate(dateString: String): GMTDate
170
171
/**
172
* Convert HTTP date string to GMTDate
173
* @param dateString HTTP date string
174
* @return GMTDate instance
175
*/
176
fun fromHttpToGmtDate(dateString: String): GMTDate
177
178
/**
179
* Convert GMTDate to HTTP date string
180
* @param date date to convert
181
* @return HTTP date string
182
*/
183
fun toHttpDate(date: GMTDate): String
184
```
185
186
**Usage Examples:**
187
188
```kotlin
189
import io.ktor.http.*
190
import io.ktor.util.date.*
191
192
// Create simple cookie
193
val sessionCookie = Cookie(
194
name = "sessionId",
195
value = "abc123def456",
196
httpOnly = true,
197
secure = true
198
)
199
200
// Create cookie with expiration
201
val persistentCookie = Cookie(
202
name = "remember_token",
203
value = "long-lived-token",
204
maxAgeInt = 30 * 24 * 3600, // 30 days
205
domain = ".example.com",
206
path = "/",
207
secure = true,
208
httpOnly = true
209
)
210
211
// Create cookie with custom attributes
212
val trackingCookie = Cookie(
213
name = "tracking",
214
value = "user-preferences",
215
extensions = mapOf(
216
"SameSite" to "Lax",
217
"Priority" to "High"
218
)
219
)
220
221
// Cookie with encoding for special characters
222
val encodedCookie = Cookie(
223
name = "data",
224
value = "value with spaces & symbols",
225
encoding = CookieEncoding.BASE64_ENCODING
226
)
227
228
// Render Set-Cookie headers (server-side)
229
val setCookieHeader1 = renderSetCookieHeader(sessionCookie)
230
// sessionId=abc123def456; HttpOnly; Secure
231
232
val setCookieHeader2 = renderSetCookieHeader(persistentCookie)
233
// remember_token=long-lived-token; Max-Age=2592000; Domain=.example.com; Path=/; HttpOnly; Secure
234
235
// Render Cookie header (client-side)
236
val cookieHeader = renderCookieHeader(sessionCookie)
237
// sessionId=abc123def456
238
239
// Parse Set-Cookie header
240
val setCookieValue = "user=john; Max-Age=3600; Path=/; HttpOnly"
241
val parsedCookie = parseServerSetCookieHeader(setCookieValue)
242
println("Name: ${parsedCookie.name}") // user
243
println("Value: ${parsedCookie.value}") // john
244
println("Max-Age: ${parsedCookie.maxAgeInt}") // 3600
245
println("HttpOnly: ${parsedCookie.httpOnly}") // true
246
247
// Parse client Cookie header
248
val clientCookieValue = "sessionId=abc123; userId=456; theme=dark"
249
val clientCookies = parseClientCookiesHeader(clientCookieValue)
250
clientCookies.forEach { (name, value) ->
251
println("$name = $value")
252
}
253
254
// Cookie value encoding/decoding
255
val originalValue = "user data with spaces"
256
val encoded = encodeCookieValue(originalValue, CookieEncoding.URI_ENCODING)
257
val decoded = decodeCookieValue(encoded, CookieEncoding.URI_ENCODING)
258
println("Original: $originalValue")
259
println("Encoded: $encoded")
260
println("Decoded: $decoded")
261
262
// Working with dates
263
val futureDate = GMTDate() + 7 * 24 * 3600 * 1000L // 7 days from now
264
val cookieWithExpiry = Cookie(
265
name = "temp_data",
266
value = "temporary",
267
expires = futureDate
268
)
269
270
// Date conversions
271
val httpDateString = toHttpDate(futureDate)
272
val cookieDateString = "Wed, 09 Jun 2021 10:18:14 GMT"
273
val parsedDate = fromCookieToGmtDate(cookieDateString)
274
275
// Cookie serialization (kotlinx.serialization support)
276
import kotlinx.serialization.*
277
import kotlinx.serialization.json.*
278
279
@Serializable
280
data class CookieContainer(val cookies: List<Cookie>)
281
282
val container = CookieContainer(listOf(sessionCookie, persistentCookie))
283
val json = Json.encodeToString(container)
284
val deserialized = Json.decodeFromString<CookieContainer>(json)
285
286
// Helper functions for common patterns
287
fun createSecureSessionCookie(sessionId: String): Cookie {
288
return Cookie(
289
name = "SESSIONID",
290
value = sessionId,
291
httpOnly = true,
292
secure = true,
293
path = "/",
294
extensions = mapOf("SameSite" to "Strict")
295
)
296
}
297
298
fun createRememberMeCookie(token: String, days: Int = 30): Cookie {
299
return Cookie(
300
name = "remember_me",
301
value = token,
302
maxAgeInt = days * 24 * 3600,
303
httpOnly = true,
304
secure = true,
305
path = "/",
306
extensions = mapOf("SameSite" to "Lax")
307
)
308
}
309
310
// Usage in HTTP responses
311
val headers = headers {
312
append(HttpHeaders.SetCookie, renderSetCookieHeader(sessionCookie))
313
append(HttpHeaders.SetCookie, renderSetCookieHeader(persistentCookie))
314
}
315
316
// Usage in HTTP requests
317
val requestHeaders = headers {
318
append(HttpHeaders.Cookie, renderCookieHeader(sessionCookie))
319
}
320
321
// Delete cookie by setting expired date
322
fun deleteCookie(name: String, domain: String? = null, path: String? = null): Cookie {
323
return Cookie(
324
name = name,
325
value = "",
326
expires = GMTDate(0), // Unix epoch
327
domain = domain,
328
path = path
329
)
330
}
331
332
val deleteCookie = deleteCookie("sessionId", path = "/")
333
val deleteHeader = renderSetCookieHeader(deleteCookie)
334
// sessionId=; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/
335
```
336
337
## Types
338
339
All types are defined above in their respective capability sections.