Skip to content

withCache

function withCache<TArgs, TResult>(fn, options): (...args) => Promise<TResult>;

Defined in: unstorage-utils.ts:102

Wrap an async function with a persistent cache layer backed by unstorage. Supports functions with any number of arguments.

A plain TTL cache, kept small on purpose: no stale-while-revalidate, and concurrent misses for the same key each call the function. When you need those, use @epic-web/cachified (stale-while-revalidate, value validation, one fetch per key for concurrent misses) or bentocache (multi-tier cache with stampede protection and grace periods); see the recommended libraries.

Type Parameter
TArgs extends unknown[]
TResult extends StorageValue
Parameter Type
fn (…args) => Promise<TResult>
options WithCacheOptions<TArgs>

(…args) => Promise<TResult>

Single arg

const loadUser = withCache(
async (id: string) => db.users.findById(id),
{ storage: createStorage(), prefix: "user", ttl: 60 },
);
await loadUser("user_123");

Multiple args

const search = withCache(
async (query: string, page: number) => api.search(query, page),
{ storage, prefix: "search", ttl: 300 },
);
await search("hello", 1);

Custom toKey

const loadUser = withCache(
async (id: string, role: string) => fetchUser(id, role),
{ storage, prefix: "user", toKey: (id) => id },
);