Skip to content

Instantly share code, notes, and snippets.

@GraemeFulton
Created June 20, 2024 19:57
Show Gist options
  • Save GraemeFulton/77823b0650080299dd7e608985539247 to your computer and use it in GitHub Desktop.
Save GraemeFulton/77823b0650080299dd7e608985539247 to your computer and use it in GitHub Desktop.
Cloudflare worker to clear cache for page
export default {
async fetch(request, env) {
const url = new URL(request.url);
const cacheKey = url.pathname;
// Check if the request is to clear cache
if (url.pathname.startsWith('/clear-cache')) {
const targetPath = url.searchParams.get('path');
if (targetPath) {
await env.MY_CACHE.delete(targetPath);
return new Response(`Cache cleared for: ${targetPath}`, { status: 200 });
} else {
return new Response('Path query parameter is required', { status: 400 });
}
}
// Handle normal requests with caching
const cache = await env.MY_CACHE.get(cacheKey);
if (cache) {
return new Response(cache, {
headers: { 'Cache-Control': 'public, max-age=3600' }
});
} else {
const response = await fetch(request);
const responseBody = await response.text();
await env.MY_CACHE.put(cacheKey, responseBody);
return new Response(responseBody, {
headers: { 'Cache-Control': 'public, max-age=3600' }
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment