Skip to content

k.session ​

Session-level storage - stores per-session data on the server side

Execution ContextPrerequisitesTypical Use
KScript APIs, Page / Layout / View server scriptsClient 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 ​

js
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 / PropertyDescriptionReturns
set(key, value)Store session entry (also k.session[key] = value)void
get(key)Read session value; returns null when missingany
containsKey(key)Check whether a session key existsboolean
remove(key)Delete a session key (always returns true)boolean
clear()Clear all keys in the current sessionvoid
keysArray of key names (null before first write)string[] | null
valuesArray of values (null before first write)any[] | null
lengthEntry 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 ​

SettingValue
StorageProcess-local in-memory (lost on restart; not shared across instances)
Cookie name_kb_session_id
Cookie expiration7 days
Server expiration30-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() updates LastModified without checking expiration, and expired-session cleanup runs only inside set() 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 <= 50 in runtime, i.e., up to 51 entries); once full, further set() writes—including updates to existing keys—are silently ignored without throwing an error.
  • Closing the browser does not clear the _kb_session_id cookie (valid for 7 days).

Methods ​

set() ​

Store a value in the current session (also supports property assignment k.session[key] = value).

ParameterTypeRequiredDescription
keystringYesSession key
valueanyYesValue to store

Returns: void.

js
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]).

ParameterTypeRequiredDescription
keystringYesSession key

Returns: any, the stored value for key, or null when missing.

js
k.api.get(() => {
  const username = k.session.get("username")
  return { username }
})

containsKey() ​

Check whether a key exists in the current session.

ParameterTypeRequiredDescription
keystringYesSession key

Returns: boolean.

js
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.

ParameterTypeRequiredDescription
keystringYesSession key

Returns: boolean. Always returns true, even if the key did not exist in the session.

js
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.

js
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.

js
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.

js
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.

js
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 ​

js
// 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 ​

ts
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;
}