Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save RafPe/737f5fd3e95858317f4e907fe79b8cbd to your computer and use it in GitHub Desktop.

Select an option

Save RafPe/737f5fd3e95858317f4e907fe79b8cbd to your computer and use it in GitHub Desktop.

Revisions

  1. @vdbelt vdbelt created this gist Aug 21, 2018.
    42 changes: 42 additions & 0 deletions cloudflare-purge-cache-service-worker.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    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
    }