Packages@g14o/cache
Examples
withCache, cache keys, invalidation, SWR, and negative caching.
Wrap a server function with withCache
withCache accepts any async function. For Result-shaped returns, successes are cached by default.
import { withCache } from "@/lib/cache";
export const getUsersCached = withCache(getUsers, {
ttl: "medium",
prefix: "users",
});Plain return values (non-Result) are cached, including undefined. Bare null is not cached (get uses null for missing keys).
Stale-while-revalidate
Serve stale data while refreshing in the background:
withCache(getUsers, {
ttl: "medium",
staleWhileRevalidate: 60,
});Negative caching (opt-in)
Cache failed Result values to avoid hammering upstream on repeated misses:
withCache(getUser, {
cacheFailures: true,
});Custom failure TTL:
withCache(getUser, {
cacheFailures: { enabled: true, ttl: "medium" },
});Parameterized cache with a custom key
import { createListCacheKey } from "@g14o/cache";
import { withCache } from "@/lib/cache";
export const listUsersCached = withCache(listUsers, {
prefix: "users",
keyGenerator: (filters) => createListCacheKey("users", filters),
ttl: "short",
});Invalidate after a mutation
import { createEntityCacheKey } from "@g14o/cache";
import { invalidateCache, invalidateCacheKey } from "@/lib/cache";
await updateUser(id, data);
await invalidateCacheKey(createEntityCacheKey("user", id));
await invalidateCache("*", { prefix: "users" });