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(βhttps://mywebsite.nyc3.digitaloceanspaces.comβ + path)
}
addEventListener(βfetchβ, event => {
event.respondWith(handleRequest(event.request))
})
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("https://mywebsite.nyc3.digitaloceanspaces.com" + path);
let newHeaders = new Headers(req.headers);
newHeaders.set("cache-control", "max-age=2592000");
newHeaders.delete("x-served-by");
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 => {
event.respondWith(handleRequest(event));
});
1 Like
Awesome! It worked like a charm. Thank you so much for your help!