Setting browser cache in a worker

I have created a worker to fetch my image assets from Digital Ocean Spaces through the Cloudflare CDN using the instructions in this support article. Essentially, it is creating a subdomain of my website pointing to my DO Spaces account.

The purpose for doing this was to increase the browser cache expiration on these assets as DO Spaces only provides 7 days of browser cache through their CDN. I initially tried creating a Page Rule to set the browser cache to 1 year but it seems that according to this post the page rule does not work since the sub request is pointing to a different domain. Is there any way to be able to set the browser cache inside the worker code? Thank you!

Post part of your code. I will try to adapt it here, I have a similar function.

Thank you for your help, it is very appreciated. The following is my worker code.

async function handleRequest(request) {
const parsedUrl = new URL(request.url)
let path = parsedUrl.pathname

let lastSegment = path.substring(path.lastIndexOf(’/’))
if (lastSegment.indexOf(’.’) === -1) {
path += ‘/index.html’
return fetch(“” + path)
addEventListener(‘fetch’, event => {

Should be something like this:

const handleRequest = async function(event) {
  const parsedUrl = new URL(event.request.url);
  let cache = caches.default;
  let response = await cache.match(event.request);
  if (!response) {
    let path = parsedUrl.pathname;
    let lastSegment = path.substring(path.lastIndexOf("/"));
    if (lastSegment.indexOf(".") === -1) {
      path += "/index.html";
    let req = await fetch("" + path);
    let newHeaders = new Headers(req.headers);
    newHeaders.set("cache-control", "max-age=2592000");
    const new_response = await new Response(req.body, {
      status: req.status,
      statusText: req.statusText,
      headers: newHeaders

    event.waitUntil(cache.put(event.request, new_response.clone()));
    return new_response;
  return response;

addEventListener("fetch", event => {
1 Like

Awesome! It worked like a charm. Thank you so much for your help!