Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cloudflare workers script to enable edge-cache. Use Official cloudflare wordpress pulgin for auto cache purge management
// Stop CF edge from caching your site when specific wordpress cookies are present
// script found in https://www.mmaton.com/2018/07/02/cloudflare-cache-anonymous-requests/
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')
// Edge Cache for 1 month
const cacheSeconds = 2592000
if (cookie
&& (
cookie.includes(`wordpress_logged`)
|| cookie.includes(`comment_`)
|| cookie.includes(`wordpress_sec`)
|| cookie.includes(`woocommerce_`)
)) {
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 {
return fetch(new Request(request, { cf: { cacheTtl: cacheSeconds } }))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.