Skip to main content

Import

import { RequestCache } from "bytekit/request-cache";

Constructor

const cache = new RequestCache(config?);

Config options

PropertyTypeDefaultDescription
ttlnumber60000Time-to-live in milliseconds for cached entries
staleWhileRevalidatebooleanfalseWhen true, stale entries are returned while a fresh value is being fetched
keyGenerator(key: string) => stringCustom function to transform cache keys before storage

Methods

MethodReturnsDescription
get<T>(key)T | undefinedReturns the cached value or undefined if missing or expired
set<T>(key, value, options?)voidStores a value under the given key
isStale(key)booleanReturns true when the entry exists but has exceeded its TTL
invalidate(key)voidRemoves a single entry by key
invalidatePattern(pattern)voidRemoves all entries whose keys match a RegExp
clear()voidRemoves every entry from the cache
getStats()CacheStatsReturns hit/miss counters and the current size
prune()voidRemoves all expired entries without waiting for a read

set options

PropertyTypeDefaultDescription
ttlnumberConstructor ttlOverride the TTL for this specific entry

getStats return value

PropertyTypeDescription
hitsnumberNumber of cache hits
missesnumberNumber of cache misses
sizenumberCurrent number of entries
hitRatenumberRatio of hits to total reads (01)

Examples

Basic read-through cache

import { ApiClient } from "bytekit/api-client";
import { RequestCache } from "bytekit/request-cache";

const api = new ApiClient({ baseUrl: "https://api.example.com" });
const cache = new RequestCache({ ttl: 30_000 });

async function getUser(id: string) {
  const key = `/users/${id}`;
  const cached = cache.get<User>(key);
  if (cached) return cached;

  const user = await api.get<User>(key);
  cache.set(key, user);
  return user;
}

Per-entry TTL override

// Cache rarely-changing config for 5 minutes
cache.set("app-config", config, { ttl: 300_000 });

// Cache volatile data for 5 seconds
cache.set("live-price", price, { ttl: 5_000 });

Pattern invalidation

// Invalidate every cached user entry after a bulk update
cache.invalidatePattern(/^\/users\//);

Stale-while-revalidate

const cache = new RequestCache({
  ttl: 60_000,
  staleWhileRevalidate: true,
});

const data = cache.get("dashboard");

if (data && cache.isStale("dashboard")) {
  // Return stale data immediately, refresh in background
  refreshDashboard().then((fresh) => cache.set("dashboard", fresh));
}

Monitoring cache performance

const stats = cache.getStats();
console.log(`Hit rate: ${(stats.hitRate * 100).toFixed(1)}%`);
console.log(`Entries: ${stats.size}`);
Call prune() on a timer if you cache many short-lived entries. This keeps memory usage predictable without affecting read performance.
RequestCache is an in-memory store. For persistent or cross-tab caching, see CacheManager.