Skip to content

Instantly share code, notes, and snippets.

@tillkruss

tillkruss/worker.js

Created Jul 17, 2018
Embed
What would you like to do?
A Cloudflare worker that allow cookie/path based caching.
/**
* 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