Support for stale-while-revalidate in Cache API
February 27, 2026
The Netlify Cache API now has full support for stale-while-revalidate (SWR). This was a previous limitation of the Cache API that has now been lifted, thanks to a request from a customer.
When using fetchWithCache with the swr option, background revalidation is handled automatically. If a response is stale but still within the SWR window, it’s served immediately while a fresh response is fetched and cached in the background.
import { fetchWithCache, DAY, HOUR } from "@netlify/cache";import type { Config, Context } from "@netlify/functions";
export default async (req: Request, context: Context) => { const response = await fetchWithCache("https://example.com/expensive-api", { ttl: 2 * DAY, swr: HOUR, tags: ["product"], }); return response;};
export const config: Config = { path: "/api/products",};For users who interact directly with cache.match and cache.put, a new needsRevalidation method lets you check whether a cached response is stale and trigger background revalidation manually:
import { needsRevalidation, cacheHeaders, MINUTE, HOUR } from "@netlify/cache";import type { Config, Context } from "@netlify/functions";
const cache = await caches.open("my-cache");
export default async (req: Request, context: Context) => { const request = new Request("https://example.com/expensive-api"); const cached = await cache.match(request);
if (cached) { if (needsRevalidation(cached)) { context.waitUntil( fetch(request).then((fresh) => { const response = new Response(fresh.body, { headers: { ...Object.fromEntries(fresh.headers), ...cacheHeaders({ ttl: MINUTE, swr: HOUR }), }, }); return cache.put(request, response); }) ); } return cached; }
const fresh = await fetch(request); const response = new Response(fresh.body, { headers: { ...Object.fromEntries(fresh.headers), ...cacheHeaders({ ttl: MINUTE, swr: HOUR }), }, });
context.waitUntil(cache.put(request, response.clone())); return response;};
export const config: Config = { path: "/api/data",};Learn more in the Cache API documentation and the caching overview.