Cache API

The Cache API allows you to control reading and writing from Edge Cache through Edge Functions.

Request headers

HeaderDescription
x-storage-operationcache-storage ops (open, has, delete)
x-cache-operationcache ops (match, put, delete, none, all)
x-storage-namecache-storage name (optional, default: "my-cache")
export async function fetch(request, env, ctx) {
const responseHeaders = { "content-type": "text/plain" };
try {
const cacheName =
request.headers.get("x-cache-name") // Prioritize header
?? env.CACHE_NAME // binding fallback
?? "default"; // final fallback
const cache = await caches.open(cacheName);
if (request.headers.get("x-clear-cache")) {
await cache.delete(request);
return new Response(null, { headers: responseHeaders, status: 205 });
}
const cachedResponse = await cache.match(request);
if (cachedResponse) return cachedResponse;
const originURL = "https://o72cj3e0vu.map.azionedge.net";
const fetchResponse = await fetch(originURL);
ctx.waitUntil(cache.put(request, fetchResponse.clone()));
return new Response(
"I couldn't load cache, because I'm a teapot!",
{ headers: responseHeaders, status: 418 }
);
} catch (err) {
console.error(err);
return new Response(err.message, { headers: responseHeaders, status: 500 });
}
}