Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@JosephHewitt
Last active November 20, 2021 14:57
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JosephHewitt/dcf0391e89c871d92764b183cfe3d0e6 to your computer and use it in GitHub Desktop.
Save JosephHewitt/dcf0391e89c871d92764b183cfe3d0e6 to your computer and use it in GitHub Desktop.
Cloudflare Worker JS code to cache Wordpress HTML for logged-out users.
/*I make no guarantees this code will work reliably. Use at your own risk. Please thoroughly test before deploying.
Enabling this on a Cloudflare Worker for a Wordpress site should cache all HTML pages (if your origin headers allow that) but bypass the cache when a user is logged in.
This is tested and working on a Wordpress 5.0.2 installation and the free Cloudflare tier (but I make no guarentees it will work for anyone else).
Sets the `x-cfw-cache` header to indicate the Worker cache status (either HIT, MISS, NO, or BYPASS): `NO` = server has set cookies (won't cache) and `BYPASS` = client has cookies (bypassing cache).
*/
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
async function handleRequest(event) {
let request = event.request;
let response = null;
cookies = request.headers.get("Cookie");
if (cookies && cookies.toLowerCase().includes("wordpress_")){
console.log("We have cookies. Don't cache.", cookies);
response = await fetch(request);
response = new Response(response.body, response);
response.headers.set("x-cfw-cache", "BYPASS");
return response;
}
let cache = caches.default;
response = await cache.match(request);
if (response && response.status !== 200){
response = null;
}
if (!response){
console.log("No cache. Will fetch.");
response = await fetch(request);
response = new Response(response.body, response);
let responsecookies = response.headers.get("Set-Cookie");
if (responsecookies && responsecookies.toLowerCase().includes("wordpress_")){
//Wordpress auth/test cookies are being set here. We don't want to cache.
response.headers.set("x-cfw-cache", "NO");
} else {
response.headers.delete("Set-Cookie"); //Cloudflare won't cache responses containing Set-Cookie.
response.headers.set("x-cfw-cache", "MISS");
if (response.status == 200){
event.waitUntil(cache.put(request, response.clone()));
}
}
} else {
response = new Response(response.body, response);
response.headers.set("x-cfw-cache", "HIT");
}
return response
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment