Custom Purge ignored if using workers rule to cache

Hey all. I’m using the below script to cache content for non-logged in users. However, if I run a custom purge from the dashboard of a URL it is ignored and the cached copy still shown.

If I turn off the workers script and run the custom purge it works fine. BUT, if I then switch on the workers script again the old, supposedly purged page, returns.

The script is as follows:

 // Stop CF edge from caching your site when specific wordpress cookies are present
addEventListener('fetch', event => {
  event.respondWith(noCacheOnCookie(event.request))
})

async function noCacheOnCookie(request) {
  // Determine which group this request is in.
  const cookie = request.headers.get('Cookie')
  const cacheSeconds = 604800
  if (cookie 
    && (
      cookie.includes(`wordpress_logged`)
      || cookie.includes(`comment_`)
      || cookie.includes(`wordpress_sec`)
    )) {
      
    const bustedRequest = new Request(request, { cf: { cacheTtl: -1 } })
    const response = await fetch(bustedRequest)

    const newHeaders = new Headers(response.headers)
    newHeaders.append('wp-cache-busted', `true`)

    return new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: newHeaders
    })
    
  } else {
    // Edge Cache for 7 days

    return fetch(new Request(request, { cf: { cacheTtl: cacheSeconds } }))
  }
}

Does anyone have a clue where I’m going wrong? Many thanks.

…I also forgot to mention that if I run a purge all (with or without the workers script on it doesn’t matter) then that works and the page is purged permanently.

This so so so hard way. You have to activate cache everything on page rules. And go workers check only if have cookies return fetch cachettl: -1

Dont forget wp-admin wp-includes and wp-content folder deactivate.

Regards.