Skip to content

Instantly share code, notes, and snippets.

@rikschennink
Created September 28, 2022 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rikschennink/4f874e59e90b1aae74c1359d3086fc6a to your computer and use it in GitHub Desktop.
Save rikschennink/4f874e59e90b1aae74c1359d3086fc6a to your computer and use it in GitHub Desktop.
Cloudflare purge cache worker
// Based on https://gist.github.com/vdbelt/20f116236d2ebffa92f131e679c0551a
addEventListener('fetch', event => {
event.respondWith(purgeCache(event.request))
})
async function purgeCache(request) {
// get zone querystring value
const zone = new URL(request.url).searchParams.get('zone');
// test if is valid zone id
if (!/^([a-z0-9]{32})$/.test(zone)) return new Response('Invalid Zone ID', { status: 500 });
// build url to target zone
const url = `https://api.cloudflare.com/client/v4/zones/${zone}/purge_cache`;
// fire the request
return await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Auth-Email': '', // cloudflare account email address
'X-Auth-Key': '' // my-profile -> api tokens -> global api key
},
body: JSON.stringify({
'purge_everything': true
})
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment