Created
September 28, 2022 11:33
-
-
Save rikschennink/4f874e59e90b1aae74c1359d3086fc6a to your computer and use it in GitHub Desktop.
Cloudflare purge cache worker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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