k.session
Session-level storage - stores per-session data on the server side
| Execution Context | Prerequisites | Typical Use |
|---|---|---|
| KScript APIs, Page / Layout / View server scripts | Client sends session cookie (_kb_session_id) | Store multi-request user session data, wizard steps, and server-side state |
k.session provides server-side session storage that persists across HTTP requests within the same user session.
Quick Start
k.api.post("login", () => {
const { username } = JSON.parse(k.request.body || "{}")
k.session.set("username", username || "guest")
return {
username: k.session.get("username"),
hasUser: k.session.containsKey("username")
}
})Quick Reference
| Method / Property | Description | Returns |
|---|---|---|
set(key, value) | Store session entry (also k.session[key] = value) | void |
get(key) | Read session value; returns null when missing | any |
containsKey(key) | Check whether a session key exists | boolean |
remove(key) | Delete a session key (always returns true) | boolean |
clear() | Clear all keys in the current session | void |
keys | Array of key names (null before first write) | string[] | null |
values | Array of values (null before first write) | any[] | null |
length | Entry count (throws if read before first write) | number |
Differences from cookie
- Session: Stored on the server; suitable for larger payloads and sensitive state.
- Cookie: Stored on the client browser; suitable for small preferences and tokens.
Lifecycle
| Setting | Value |
|---|---|
| Storage | Process-local in-memory (lost on restart; not shared across instances) |
| Cookie name | _kb_session_id |
| Cookie expiration | 7 days |
| Server expiration | 30-minute inactivity threshold with lazy cleanup (swept on set() at most every 60 minutes) |
Behavior:
- Process-local memory: Session data lives only in the current server process's memory—it is cleared on restart and is not shared across multiple server instances or workers.
- Lazy expiration:
get()updatesLastModifiedwithout checking expiration, and expired-session cleanup runs only insideset()at most once every 60 minutes (removing sessions idle for over 30 minutes). As a result, idle sessions may remain readable past 30 minutes until the next cleanup sweep runs. - Key limit: Each session allows around 50 keys (
Count <= 50in runtime, i.e., up to 51 entries); once full, furtherset()writes—including updates to existing keys—are silently ignored without throwing an error. - Closing the browser does not clear the
_kb_session_idcookie (valid for 7 days).
Methods
set()
Store a value in the current session (also supports property assignment k.session[key] = value).
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Session key |
value | any | Yes | Value to store |
Returns: void.
k.api.get(() => {
k.session.set("username", "kooboo")
k.session.set("role", "admin")
return "session set"
})get()
Read a value from the current session (also supports property access k.session[key]).
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Session key |
Returns: any, the stored value for key, or null when missing.
k.api.get(() => {
const username = k.session.get("username")
return { username }
})containsKey()
Check whether a key exists in the current session.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Session key |
Returns: boolean.
k.api.get(() => {
k.session.set("token", "abc123")
const hasToken = k.session.containsKey("token")
return { hasToken }
})remove()
Delete a specified key from the current session.
| Parameter | Type | Required | Description |
|---|---|---|---|
key | string | Yes | Session key |
Returns: boolean. Always returns true, even if the key did not exist in the session.
k.api.get(() => {
k.session.set("temp", "data")
const removed = k.session.remove("temp")
return { removed, stillExists: k.session.containsKey("temp") }
})clear()
Remove all entries from the current session.
Parameters: None.
Returns: void.
k.api.get(() => {
k.session.set("key1", "value1")
k.session.clear()
return "cleared"
})Properties
keys
Return an array of all keys in the current session, or null before any key has been written.
k.api.get(() => {
k.session.set("key1", "value1")
k.session.set("key2", "value2")
return { keys: k.session.keys }
})
// Returns: { "keys": ["key1", "key2"] }values
Return an array of all values in the current session, or null before any key has been written.
k.api.get(() => {
k.session.set("key1", "value1")
k.session.set("key2", "value2")
return { values: k.session.values }
})
// Returns: { "values": ["value1", "value2"] }length
Return the number of stored key-value pairs. Accessing length before any key has been written in the session throws an error; check k.session.keys first when the session may be empty.
k.api.get(() => {
k.session.set("key1", "value1")
k.session.set("key2", "value2")
return { length: k.session.length }
})
// Returns: { "length": 2 }Complete Example
User Login Status
// Set API URL to /api/session/{action}
// Login (POST /api/session/login)
k.api.post("login", () => {
let body = {}
try {
body = JSON.parse(k.request.body || "{}")
} catch (e) {
k.response.statusCode(400)
return { success: false, error: "Invalid JSON body" }
}
const user = { id: "123", name: body.username || "guest", role: "admin" }
k.session.set("user", JSON.stringify(user))
return { success: true, user }
})
// Check login status (GET /api/session/status)
k.api.get("status", () => {
const userStr = k.session.get("user")
if (userStr) {
const user = JSON.parse(userStr)
return { loggedIn: true, user }
}
return { loggedIn: false, user: null }
})
// Log out (GET /api/session/logout)
k.api.get("logout", () => {
k.session.remove("user")
return { success: true }
})TypeScript Definitions
interface Session extends Record<string, any> {
keys: string[];
values: any[];
length: number;
set(key: string, value: any): void;
get(key: string): any;
containsKey(key: string): boolean;
remove(key: string): boolean;
clear(): void;
}