Skip to content

Instantly share code, notes, and snippets.

@boertel
Created December 6, 2024 23:37
Show Gist options
  • Save boertel/ec56319f5f4dbec28b750cbda3fe0027 to your computer and use it in GitHub Desktop.
Save boertel/ec56319f5f4dbec28b750cbda3fe0027 to your computer and use it in GitHub Desktop.
Cloudflare Pages Cache middleware
export const onRequest = [
async function cache({ request, next, waitUntil, }) {
if (request.method === "GET") {
const cache = caches.default;
const cachedResponse = await cache.match(request);
if (cachedResponse) {
console.log("cache HIT", request.url);
return cachedResponse;
}
}
console.log("cache MISS", request.url);
const response = await next();
if (response) {
const cache = caches.default;
waitUntil(cache.put(request, response.clone()));
}
return response;
},
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment