The Workers doc are of course a good place to start.
When a Worker receives a HTTP request (like for a HTML page or .css file), it will need to get those resources from your origin server with the fetch()
function.
Since that is a request, you can configure the fetch()
operation with several of the properties listed here, including cacheTtl
which is the time (in seconds) that Cloudflare caches the assets in the data centre where the request happened.
You can then modify the response you get from the origin by setting the Cache-Control
header to, for example, 5 minutes.
Here is a quick demo with the following code:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a given request object
* @param {Request} request
*/
async function handleRequest(request) {
// Make request and store on Cloudflare POP for one month
const response = await fetch(request, { cf: {
cacheTtl: 2592000
}});
// Adjust headers from origin to return to browser
const newHeaders = new Headers(response.headers);
// Set browser caching to 5 minutes
newHeaders.set("Cache-Control", "public, immutable, max-age=300");
// Return updated response
return new Response(response.body, {
headers: newHeaders,
method: request.method,
status: response.status
});
}
Note that this approach does depend on purging the cache given the long caching period that Cloudflare uses on its CDN.
(With the Cloudflare API you can purge 30 URLs at a time, in case one person’s published Obsidian needs to be removed.)