I am trying to implement cloudflare workers to bypass cache based on cookie for loggedin user. Implementation seems to be working but I am not able to login. I get Error 1101 while login
Here is my code :
const BYPASS_COOKIE_PREFIXES = [
“wp-”,
“wordpress”,
“comment_”,
“woocommerce_”,
“affwp_”,
“mautic”
];
// 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 cookieHeader = request.headers.get(‘Cookie’)
const cacheSeconds = 604800
let needsBypass = false;
if (cookieHeader && cookieHeader.length && BYPASS_COOKIE_PREFIXES.length) {
const cookies = cookieHeader.split(’;’);
for (let cookie of cookies) {
// See if the cookie starts with any of the logged-in user prefixes
for (let prefix of BYPASS_COOKIE_PREFIXES) {
if (cookie.trim().startsWith(prefix)) {
needsBypass = true;
break;
}
}
if (needsBypass) {
break;
}
}
}
if (needsBypass) {
let init = {
method: request.method,
headers: […request.headers],
// redirect: “manual”,
body: request.body,
cf: { cacheTtl: 0 }
};
let uniqueUrl = await generateUniqueUrl(request);
let newRequest = new Request(uniqueUrl, init);
// newRequest.headers.set(‘Cache-Control’, ‘no-cache, no-store’);
// For debugging, clone the response and add some debug headers
let response = await fetch(newRequest);
let newResponse = new Response(response.body, response);
newResponse.headers.set('X-Bypass-Cache', 'Bypassed');
newResponse.headers.set('wp-cache-busted', `true`)
return newResponse;
} else {
// Edge Cache for 7 days
return fetch(new Request(request, { cf: { cacheTtl: cacheSeconds } }))
}
}
/**
- Generate a unique URL so it will never match in the cache.
- This is a bit of a hack since there is no way to explicitly bypass the Cloudflare cache (yet)
- and requires that the origin will ignore unknown query parameters.
-
@param {Request} request - Original request
*/
async function generateUniqueUrl(request) {
let url = request.url;
let timeInMs = Date.now();
let hashString = ‘’;
for (let header of request.headers) {
hashString += header[0] + ‘: ’ + header[1] + ‘\n’;
}
const encoder = new TextEncoder();
const digest = await crypto.subtle.digest(‘SHA-512’, encoder.encode(hashString));
const base64digest = btoa(String.fromCharCode(…new Uint8Array(digest)));
const unique = encodeURIComponent(base64digest) + ‘.’ + timeInMs;
if (url.indexOf(’?’) >= 0) {
url += ‘&’;
} else {
url += ‘?’;
}
url += ‘cf_cache_bust=’ + unique;
return url;
}