Skip to content

k.cache ​

Site-wide in-memory cache, shared across requests within the same site

Execution ContextPrerequisitesTypical Use
KScript APIs, Page / Layout / View server scriptsIn-memory server cache isolated per siteCache expensive queries, API results, and external asset URLs

k.cache stores key-value pairs in server memory, isolated per current site (grouped internally by site ID). On a cache miss, get() returns undefined (pair with containsKey() when cached values may be falsy).

Quick Start ​

js
k.api.get(() => {
  const key = "summary-" + (k.request.queryString.get("id") || "default")
  return k.cache.getOrCreate(
    key,
    () => ({ generatedAt: Date.now(), ok: true }),
    300
  )
})

Quick Reference ​

Method / PropertyDescriptionReturns
groupRead-only opaque cache group identifier for current sitestring
set(key, value[, seconds | options])Store entry in cache (2 args default ~120 minutes)void
get(key)Read cached entry; returns undefined on missany
getOrCreate(key, factory[, seconds | options])Compute, store, and return entry on cache missany
containsKey(key)Check whether cache key existsboolean
remove(key)Delete a single cache entryvoid
removeAll()Invalidate current site entries stored via set(key, value[, seconds]) or getOrCreate(..., seconds)void
localCache(externalUrl, hours)Register external URL and return local site URL (fetched and cached on first request)string
getOrSet(key, script, TimeOutMinutes)Applies duration in seconds; returns undefined on miss (use getOrCreate instead)any

Differences from k.session

APIStorageTypical uses
k.cacheSite in-memory cache with optional TTL in secondsHot data, computed results, site-wide sharing
k.sessionVisitor-scoped session storageShopping carts, pre-login visitor state

group ​

Read-only group identifier used by the current site's cache. It stays stable within the same site and isolates cache keys from other sites. Treat it as an opaque string; do not parse it or depend on its format.

Returns: string.

js
k.api.get(() => {
  return { group: k.cache.group }
})

set() ​

Write an entry to the cache.

OverloadDescription
set(key, value, seconds)Expires after seconds (absolute expiration)
set(key, value)Defaults to approximately 120 minutes
set(key, value, options)Configures expiration through an Options object

Keys can be up to 1024 characters long. The seconds argument in set(key, value, seconds) is capped by the server's Cache:MaxExpireSeconds setting (about 2 hours by default).

ParameterTypeRequiredDescription
keystringYesCache key
valueanyYesValue to cache
secondsnumberNoExpiration in seconds
optionsOptionsNoExpiration options object

Returns: void.

js
k.api.post(() => {
  const key = "summary-" + Date.now()
  k.cache.set(key, { ok: true }, 60)
  return {
    stored: k.cache.containsKey(key),
    value: k.cache.get(key)
  }
})

Options Overload (set / getOrCreate) ​

When passing an Options object as the third argument, you can pass absoluteExpiration or slidingExpiration. Both properties map to C# TimeSpan? and expect TimeSpan string format (such as "00:05:00" for 5 minutes) or null — do not pass numeric seconds.

  • set(key, value, seconds) automatically binds the current site cascade token and absolute expiration, and is the recommended form for regular script caching.
  • Cascade cannot be constructed from a plain JavaScript object literal (passing { cascades: [...] } throws a missing-constructor error), so omit cascades from script option literals. Because the Options overloads (set(key, value, options) and getOrCreate(key, factory, options)) do not attach the site's cascade token automatically, removeAll() will NOT clear entries written via Options; remove them explicitly with remove(key) or let them expire via options.
js
k.api.post(() => {
  const key = "opt-" + Date.now()
  k.cache.set(key, { ok: true }, { absoluteExpiration: "00:05:00", slidingExpiration: null })
  const value = k.cache.get(key)
  k.cache.remove(key)
  return { value }
})

get() ​

Read a cached value; returns undefined when missing.

ParameterTypeRequiredDescription
keystringYesCache key

Returns: any, the cached value, or undefined on a miss.

js
k.api.get(() => {
  const key = k.request.queryString.get("key")
  return k.cache.get(key)
})

getOrCreate() ​

Execute factory on a cache miss, store the result, and return it.

OverloadDescription
getOrCreate(key, factory, seconds)Expiration in seconds (most common)
getOrCreate(key, factory, options?)Uses an Options configuration object
ParameterTypeRequiredDescription
keystringYesCache key
factoryFunctionYesFactory callback invoked on a miss; its return value is cached
secondsnumberNoExpiration in seconds
optionsOptionsNoExpiration options object

Returns: any, the cached value or newly created value returned by factory.

js
k.api.get(() => {
  const id = k.request.queryString.get("id") || "default"
  const key = "expensive-" + id
  const value = k.cache.getOrCreate(
    key,
    () => {
      return { computedAt: Date.now(), id }
    },
    300
  )
  return value
})

containsKey() ​

Check whether a cache key exists.

ParameterTypeRequiredDescription
keystringYesCache key

Returns: boolean.

js
k.api.get(() => {
  return { exists: k.cache.containsKey("my-key") }
})

remove() / removeAll() ​

remove(key) deletes one entry; removeAll() invalidates entries for the current site stored via set(key, value), set(key, value, seconds), or getOrCreate(key, factory, seconds) (it does not clear entries written via the Options overload, which must be deleted with remove(key) or expire via options).

MethodParametersReturnsDescription
remove(key)key: stringvoidDelete one cached entry
removeAll()NonevoidClear site-cascaded cache entries (excludes Options overload entries)
js
k.api.post(() => {
  const key = "rm-" + Date.now()
  k.cache.set(key, 1, 60)
  k.cache.remove(key)
  return { exists: k.cache.containsKey(key) }
})

localCache() ​

Registers an external URL for local site caching and returns a local site URL. Calling localCache() does not trigger an eager download; the resource is fetched and cached on demand when the returned local URL is first requested.

ParameterTypeRequiredDescription
externalUrlstringYesExternal resource URL
hoursnumberYesLocal cache lifetime in hours

Returns: string, a local site URL.

js
k.api.get(() => {
  const url = k.cache.localCache("https://example.com/asset.png", 24)
  return { localUrl: url }
})

getOrSet() ​

Read or cache a value by script line. Although the parameter is named TimeOutMinutes, the value is forwarded directly as seconds to set(key, obj, seconds); additionally, on a cache miss get(key) returns undefined (non-null in the underlying runtime), so calling getOrSet() on an uncached key returns undefined without executing scriptOrFunctionName. For factory-computed caching, use getOrCreate().

ParameterTypeRequiredDescription
keystringYesCache key
scriptOrFunctionNamestringYesScript expression string
TimeOutMinutesnumberYesDuration (applied in seconds)

Returns: any, the cached value on a hit, or undefined on a miss.

js
// Recommended alternative using getOrCreate:
const data = k.cache.getOrCreate("report-summary", () => {
  return k.DB.sqlite.query("SELECT 1")
}, 1800)

TypeScript Definitions ​

ts
interface KCache extends MemoryCacheBase {
  readonly group: string;
  set(key: string, value: any, seconds: number): void;
  set(key: string, value: any): void;
  set(key: string, value: any, options: Options): void;
  get(key: string): any;
  getOrCreate(key: string, factory: Function, seconds: number): any;
  getOrCreate(key: string, factory: any, options?: Options): any;
  remove(key: string): void;
  removeAll(): void;
  containsKey(key: string): boolean;
  localCache(externalUrl: string, hours: number): string;
  getOrSet(key: string, scriptOrFunctionName: string, TimeOutMinutes: number): any;
}

interface Options {
  absoluteExpiration?: string | null; // C# TimeSpan? string format, e.g. "00:05:00"
  slidingExpiration?: string | null;  // C# TimeSpan? string format, e.g. "00:01:00"
  cascades?: Cascade[];
}

interface Cascade {
  key: string;
  removeChangeToken: boolean;
}