k.cookie
Cookie management - reading, writing, and deleting client cookies
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
| KScript APIs, Page / Layout / View server scripts | HTTP request/response context | Persist client preferences, lightweight state, and remove domain cookies |
k.cookie provides methods to read, create, update, and remove HTTP cookies on the client for user preferences and lightweight state tracking. To integrate with site cookie consent banners and script categorization, see k.privacy.
Quick Start
k.api.get("demo", () => {
// Read the cookie sent on the incoming request
const previousTheme = k.cookie.get("theme")
const hadTheme = k.cookie.containsKey("theme")
// Emit a Set-Cookie response header (takes effect on the next request)
k.cookie.set("theme", "dark", 30)
return {
previousTheme,
hadTheme,
nextTheme: "dark"
}
})Same-request read/write behavior
k.cookie.set(), setByMinutes(), remove(), and clear() only write Set-Cookie headers to the HTTP response and do not mutate incoming request cookies. Calling k.cookie.get() or containsKey() later in the same request still reads the values received on the current request (or null / false if absent); the updated cookie becomes readable on subsequent client requests.
Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
set(name, value[, days[, domain]]) | Write a cookie (2 args default 1 day; empty deletes) | void |
setByMinutes(name, value, mins) | Set a cookie expiring after N minutes | void |
get(Name) | Read incoming request cookie value; null if missing | string | null |
containsKey(key) | Check whether a cookie exists on the current request | boolean |
remove(key[, domain, sameSite?]) | Queue deletion header for a cookie (always returns true) | boolean |
clear() | Delete all incoming request cookies (including system/session cookies) | void |
keys | Array of incoming request cookie names | string[] |
values | Array of incoming request cookie values | string[] |
Differences from session
- Cookie: Stored on the client browser with an explicit expiration time (generally keep values under 4 KB).
- Session: Stored on the server and cleared when the session expires.
Methods
set()
Set a cookie. Supports 2-argument (defaults to 1 day), 3-argument (explicit days), and 4-argument (explicit days and domain) overloads.
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
name | string | Yes | - | Cookie name |
value | string | Yes | - | Cookie value |
days | number | No | 1 (2-arg overload) | Expiration in days |
domain | string | No | Current domain | Cookie domain |
Returns: void.
Empty value deletion
Calling the 2-argument k.cookie.set(name, value) overload with an empty or whitespace-only value deletes the cookie by emitting expired Set-Cookie headers.
// Example API URL: /api/cookie/{action}
// Default 1-day expiration
k.api.get("default", () => {
k.cookie.set("theme", "dark")
return "cookie set for 1 day"
})
// Set a cookie that expires in 30 days
k.api.get("days", () => {
k.cookie.set("theme", "dark", 30)
return "cookie set"
})
// Set a cookie with a domain
k.api.get("domain", () => {
k.cookie.set("locale", "en-US", 7, ".example.com")
return "cookie with domain set"
})setByMinutes()
Set a cookie with expiration specified in minutes.
| Parameter | Type | Required | Description |
|---|---|---|---|
name | string | Yes | Cookie name |
value | string | Yes | Cookie value |
mins | number | Yes | Expiration in minutes |
Returns: void.
k.api.get(() => {
// Set a cookie that expires in 4 hours
k.cookie.setByMinutes("token", "xyz789", 240)
return "cookie set for 240 minutes"
})get()
Get a cookie value by name.
| Parameter | Type | Required | Description |
|---|---|---|---|
Name | string | Yes | Cookie name |
Returns: string | null, the cookie value when found, or null when missing.
k.api.get(() => {
const username = k.cookie.get("username")
return { username }
})containsKey()
Check whether a cookie exists.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cookie name |
Returns: boolean.
k.api.get(() => {
const hasToken = k.cookie.containsKey("token")
return { hasToken }
})remove()
Delete a specified cookie, optionally specifying its domain and sameSite flag.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Cookie name |
domain | string | No | Target cookie domain |
sameSite | boolean | No | Whether to emit SameSite=None; Secure deletion attributes |
Returns: boolean. Always returns true (meaning the deletion Set-Cookie header was queued on the response, regardless of whether the cookie existed).
// Example API URL: /api/cookie/{action}
// Remove cookie on current domain
k.api.get("remove-current", () => {
const queued = k.cookie.remove("theme")
return { queued }
})
// Remove cookie for a specific domain
k.api.get("remove-domain", () => {
const queued = k.cookie.remove("locale", ".example.com", false)
return { queued }
})clear()
Queue deletion headers for all cookies present on the incoming request.
Use clear() with caution
clear() iterates over k.cookie.keys from the incoming request and deletes every cookie—including Kooboo system, session, and authentication cookies (such as _kb_session_id, _site_culture, and login token cookies), which can unexpectedly log users out or drop session state. It also does not cancel new cookies appended earlier in the same response unless they were already present on the request. Prefer k.cookie.remove(key) for specific application cookies.
Parameters: None.
Returns: void.
k.api.get(() => {
k.cookie.clear()
return "all request cookies cleared"
})Properties
keys
Get the list of all cookie names.
k.api.get(() => {
return k.cookie.keys
})
// Returns: ["_site_culture", "_site_id_", "username"]values
Get the list of all cookie values.
k.api.get(() => {
return k.cookie.values
})
// Returns: ["zh-CN", "abc123...", "kooboo"]Complete Example
Site UI Preferences
// Set API URL to /api/prefs/{action}; never store user identity or auth state in unsigned cookies
// Save UI preferences (POST /api/prefs/save)
k.api.post("save", () => {
let body = {}
try {
body = JSON.parse(k.request.body || "{}")
} catch (e) {
k.response.statusCode(400)
return { success: false, error: "Invalid JSON body" }
}
const theme = body.theme === "dark" ? "dark" : "light"
const lang = typeof body.lang === "string" && body.lang ? body.lang : "en-US"
k.cookie.set("ui_theme", theme, body.remember ? 30 : 1)
k.cookie.set("ui_lang", encodeURIComponent(lang), 30)
return { success: true, preferences: { theme, lang } }
})
// Read UI preferences from the incoming request (GET /api/prefs/get)
k.api.get("get", () => {
const theme = k.cookie.get("ui_theme") || "light"
const rawLang = k.cookie.get("ui_lang")
const lang = rawLang ? decodeURIComponent(rawLang) : "en-US"
return { theme, lang }
})
// Reset UI preferences (GET /api/prefs/reset)
k.api.get("reset", () => {
k.cookie.remove("ui_theme")
k.cookie.remove("ui_lang")
return { success: true }
})Notes
- Size limit: Individual cookie values should generally stay under 4 KB.
- Security: Never store sensitive data, user identity, or unsigned authorization state in cookies (clients can forge or edit cookie values; use k.account or k.session instead).
- Domain rules: Cross-subdomain cookies require the matching
domainargument when setting and removing. - Encoding: Use
encodeURIComponent/decodeURIComponentwhen storing non-ASCII text or special characters.
TypeScript Definitions
interface Cookie {
keys: string[];
values: string[];
set(name: string, value: string, days: number): void;
set(name: string, value: string, days: number, domain: string): void;
setByMinutes(name: string, value: string, mins: number): void;
set(name: string, value: string): void;
get(Name: string): string;
containsKey(key: string): boolean;
remove(key: string): boolean;
remove(key: string, domain: string, sameSite?: boolean): boolean;
clear(): void;
}Related Docs
- k.privacy — Cookie consent settings and script classification
- k.session — Server-side session management
- k.request — HTTP request information
- k.response — HTTP response handling