-
-
Save vdbelt/20f116236d2ebffa92f131e679c0551a to your computer and use it in GitHub Desktop.
addEventListener('fetch', event => { | |
event.respondWith(purgeCache(event.request)) | |
}) | |
async function purgeCache(request) { | |
const url = new URL(request.url) | |
// If the path doesn't begin with our protected prefix, just pass the request through. | |
if (!url.pathname.startsWith("/__purge_cache")) { | |
return fetch(request) | |
} | |
// Lets validate the zone id, and return an error if invalid | |
let zoneIdValidated = (new RegExp("^([a-z0-9]{32})$")).test(url.searchParams.get('zone')); | |
if (!zoneIdValidated) { | |
return new Response('Invalid Zone ID', { | |
status: 500 | |
}); | |
} | |
let content = '{"purge_everything":true}' | |
let headers = { | |
'Content-Type': 'application/json', | |
'X-Auth-Email': '', // Cloudflare API Auth Email | |
'X-Auth-Key': '' //Cloudflare API Auth Key | |
} | |
const init = { | |
method: 'POST', | |
headers: headers, | |
body: content | |
} | |
const response = await fetch('https://api.cloudflare.com/client/v4/zones/'+url.searchParams.get('zone')+'/purge_cache', init) | |
return response | |
} |
Have you set up a worker route for /__purge_cache
on your domain?
https://developers.cloudflare.com/workers/platform/routing/routes/
I have the default route Cloudflare creates when adding a new worker: https://my-worker.xxxxxxxxxx.workers.dev/
Going to the URL https://my-worker.xxxxxxxxxx.workers.dev/__purge_cache?zone=XX shows a JSON file. Is that okay or should I try adding a new subdomain for a different worker route?
Yes. A json file should be ok.
Hi, is it possible to skip a folder from clearing cache. For example, i have images in a folder domain.com/images which doesn't change. I want to skip this folder and clear remaining cache files.
Cloudflare announced the deprecation of Wrangler v1 from Cloudflare Workers.
Is this script affected because of that?
No
Hi Martin. I can't get this to work properly.
When testing the worker from the Cloudflare dashboard I'm getting this result:
But when using the link https://example.com/__purge_cache?zone=XX I'm getting a 404 error on my WordPress installation and nothing gets purged.
Any idea what could be happening?