Composable caching primitives with TTL, stale-while-revalidate, and HTTP response caching. Zero framework dependencies — works with any runtime that has standard Request/Response.
Tip
📖 Head to the documentation to learn more.
- 🗃️ Function caching — wrap any function with TTL, stale-while-revalidate, and request deduplication.
- 🌐 HTTP response caching — automatic
etag,last-modified, and304 Not Modifiedsupport. - 🔑 Smart cache keys — derived from arguments or request URL, with per-header and per-query variance.
- 🔌 Pluggable storage — bring your own backend via a minimal
get/setinterface. - ♻️ Invalidation & expiration — remove or mark entries stale on demand, with SWR background refresh.
Wrap any function with defineCachedFunction to add caching with TTL, stale-while-revalidate, and request deduplication:
import { defineCachedFunction } from "ocache";
const cachedFetch = defineCachedFunction(
async (url: string) => {
const res = await fetch(url);
return res.json();
},
{
maxAge: 60, // Cache for 60 seconds
name: "api-fetch",
},
);
// First call hits the function, subsequent calls return cached result
const data = await cachedFetch("https://api.example.com/data");Note
Learn more in the Caching Functions guide, and see Invalidation & Expiration and Storage.
Wrap HTTP handlers with defineCachedHandler for automatic response caching with etag, last-modified, and 304 Not Modified support:
import { defineCachedHandler } from "ocache";
const handler = defineCachedHandler(
async (event) => {
// event.req is a standard Request object
const url = event.url ?? new URL(event.req.url);
const data = await getExpensiveData(url.pathname);
return new Response(JSON.stringify(data), {
headers: { "content-type": "application/json" },
});
},
{
maxAge: 300, // Cache for 5 minutes
swr: true,
staleMaxAge: 600,
varies: ["accept-language"], // Vary cache key by these headers (also emitted as `Vary`)
allowQuery: ["color"], // Vary cache by these query params only
},
);Note
Learn more in the Caching HTTP Handlers guide, and see Query Parameters, Cookies, Cache-Control & Eligibility, and Incremental Static Regeneration.
type CachedEventHandler<E extends HTTPEvent = HTTPEvent> = EventHandler<E> &Cached event handler returned by defineCachedHandler.
An EventHandler augmented with on-demand revalidation methods forwarded from
the underlying cached function. Each accepts the HTTPEvent directly and derives
the exact storage key the handler caches under, so no manual key reconstruction is needed.
const cachedFunction = defineCachedFunction;Alias for defineCachedFunction.
type CacheStatus = "hit" | "stale" | "revalidated" | "miss";How a cached value was served on a given call.
"hit"— a fresh cached value was returned without re-resolving."stale"— a stale value was served while a background SWR refresh runs."revalidated"— a prior value existed but was expired/invalid, so it was re-resolved in the foreground (no stale value served) before returning."miss"— the value was resolved fresh on this call (nothing was cached).
function createMemoryStorage(opts: MemoryStorageOptions =Creates an in-memory storage backed by a Map with optional TTL support (in seconds) and LRU eviction.
function defineCachedFunction<T, ArgsT extends unknown[] = any[]>(
fn: (...args: ArgsT) => T | Promise<T>,
opts: CacheOptions<T, ArgsT> =Wraps a function with caching support including TTL, SWR, integrity checks, and request deduplication.
Parameters:
fn— The function to cache.opts— Cache configuration options.
Returns: — A cached function with a .resolveKey(...args) method for cache key resolution.
function defineCachedHandler<E extends HTTPEvent = HTTPEvent>(
handler: EventHandler<E>,
opts: CachedEventHandlerOptions<E> =Wraps an HTTP event handler with response caching.
Automatically generates cache keys from the URL path and variable headers,
sets cache-control, etag, and last-modified headers, and handles
304 Not Modified responses via conditional request headers.
Parameters:
handler— The event handler to cache.opts— Cache and HTTP-specific configuration options.
Returns: — A new event handler that serves cached responses when available. The handler
also exposes .resolveKeys(event), .invalidate(event), and .expire(event) for
on-demand revalidation, keyed exactly as the handler caches (no key reconstruction).
type EventHandler<E extends HTTPEvent = HTTPEvent> = (Handler function that receives an HTTPEvent and returns a response value.
async function expireCache<ArgsT extends unknown[] = any[]>(
input:Expires cached entries for given arguments and cache options across all base prefixes, without removing them.
Unlike invalidateCache (which removes entries entirely), expired entries keep
serving the stale value with SWR — still bounded by the originally configured
staleMaxAge window — while the next access triggers a background refresh.
Without SWR, the next call re-resolves before returning.
Uses the same key derivation as defineCachedFunction / resolveCacheKeys.
Pass the same maxAge / swr / staleMaxAge options you cache with so the
remaining storage TTL is preserved.
Parameters:
input— Object withoptions(cache options) and optionalargs(function arguments).
Example:
// Mark a cached entry for background refresh on next access
await expireCache({
options: { name: "fetchUser", getKey: (id: string) => id, maxAge: 60, staleMaxAge: 300 },
args: ["user-123"],
});async function invalidateCache<ArgsT extends unknown[] = any[]>(
input:Invalidates (removes) cached entries for given arguments and cache options across all base prefixes.
Uses the same key derivation as defineCachedFunction / resolveCacheKeys.
Parameters:
input— Object withoptions(cache options) and optionalargs(function arguments).
Example:
// Invalidate a specific cached entry
await invalidateCache({
options: { name: "fetchUser", getKey: (id: string) => id },
args: ["user-123"],
});async function resolveCacheKeys<ArgsT extends unknown[] = any[]>(
input:Resolves all cache storage keys (one per base prefix) for given arguments and cache options.
Uses the same key derivation as defineCachedFunction internally:
- When
opts.getKeyis provided, it is called withargsto produce the key segment. - Otherwise,
argsare hashed withohash(same default asdefineCachedFunction).
Pass the same getKey, name, group, and base options you use in
defineCachedFunction / defineCachedHandler to get the exact storage keys.
Parameters:
input— Object withoptions(cache options) and optionalargs(function arguments).
Returns: — An array of storage key strings (one per base prefix).
Example:
const keys = await resolveCacheKeys({
options: { name: "fetchUser", getKey: (id: string) => id },
args: ["user-123"],
});
for (const key of keys) {
await useStorage().set(key, null); // invalidate all tiers
}function setStorage(storage: StorageInterface): void;Sets a custom storage implementation to be used by all cached functions.
function useStorage(): StorageInterface;Returns the current storage instance. If none has been set via setStorage, lazily initializes an in-memory storage.
local development
Published under the MIT license 💛.