Forked from vdbelt/cloudflare-purge-cache-service-worker.js
Last active
October 29, 2023 13:24
-
-
Save planetahuevo/92ee1450e624741b7ffb003be58ac1fa to your computer and use it in GitHub Desktop.
A CloudFlare service worker that proxies purge cache requests. Example: https://example.com/__purge_cache?zone=XX
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
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: 403 | |
}); | |
} | |
// add here additional auth to prevent missuse | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment