Created
July 17, 2018 16:18
-
-
Save tillkruss/10b11435defa77d57a37b0dd0385e201 to your computer and use it in GitHub Desktop.
A Cloudflare worker that allow cookie/path based caching.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Time-to-live in seconds for cached requests. | |
*/ | |
const cacheTtl = 300; | |
/** | |
* List of request paths to cache. | |
*/ | |
const cachedPaths = [ | |
'/', | |
'/about', | |
'/contact', | |
]; | |
addEventListener('fetch', event => { | |
event.respondWith(fetchWithCacheTtl(event.request)); | |
}); | |
/** | |
* Fetches the request after determining whether the request should | |
* be cached and appends `X-Edge-Cache` to the response. | |
* | |
* @param {Request} | |
* @return {Response} | |
*/ | |
async function fetchWithCacheTtl(request) { | |
const cacheRequest = requestShouldBeCached(request); | |
const response = await fetch(request, { | |
cf: { cacheTtl: cacheRequest ? cacheTtl : -1 } | |
}); | |
let modifiedHeaders = new Headers(response.headers); | |
modifiedHeaders.set('X-Edge-Cache', cacheRequest ? 'HIT' : 'BYPASS'); | |
return new Response(response.body, { | |
status: response.status, | |
statusText: response.statusText, | |
headers: modifiedHeaders, | |
}); | |
} | |
/** | |
* Determines whether the request should be cached. | |
* | |
* @param {Request} | |
* @return {boolean} | |
*/ | |
function requestShouldBeCached(request) { | |
if (request.method !== 'GET') { | |
return false; | |
} | |
const url = new URL(request.url); | |
const path = url.pathname === '/' ? url.pathname : url.pathname.replace(/\/$/, ''); | |
if (! cachedPaths.includes(path)) { | |
return false; | |
} | |
const cookies = request.headers.get('Cookie') || ''; | |
// The `batch` indicates whether a user is or was logged-in | |
if (cookies.includes('batch')) { | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment