Use stale-while-revalidate to return cached values during background updates
mainThe staleWhileRevalidate option allows you to specify a time window where a cached value is returned even if its ttl has expired. During this window, cachified triggers a background refresh via getFreshValue so the next caller receives the updated data. This prevents latency spikes for users when the cache expires.
import { cachified } from '@epic-web/cachified';
const cache = new Map();
function getUserById(userId: number) {
return cachified({
ttl: 120_000 /* Two minutes */,
staleWhileRevalidate: 300_000 /* Five minutes */,
cache,
key: `user-${userId}`,
async getFreshValue() {
const response = await fetch(
`https://jsonplaceholder.typicode.com/users/${userId}`,
);
return response.json();
},
});
}