Skip to content

Instantly share code, notes, and snippets.

@jonarnes
Last active March 14, 2024 12:11
Show Gist options
  • Save jonarnes/26805a285a803f0a0a646fe88456e701 to your computer and use it in GitHub Desktop.
Save jonarnes/26805a285a803f0a0a646fe88456e701 to your computer and use it in GitHub Desktop.
Use ImageEngine to optimize images through Cloudflare workers. A starting point which aligns the cache key computation on both sides
addEventListener('fetch', event => {
if (event.request.url.match(/\.(jpe?g|png|gif|svg|webp|avif|jxl)/i) && event.request.method === "GET") {
event.respondWith(handleRequest(event));
}else{
event.respondWith(fetch(event.request));
}
})
async function handleRequest(event) {
const request = event.request;
const url = new URL(request.url);
const path = url.pathname + url.search;
//defined as environment variable
const imageEngineURL = `https://${IMAGEENGINE_DELIVERY_ADDRESS}${path}`;
// Compute a custom cache key based on the URL and header
const cacheKey = url+request.headers.get('Accept')
+request.headers.get('Accept')
+request.headers.get('sec-ch-width')
+request.headers.get('sec-ch-dpr')
+request.headers.get('sec-ch-viewport-width')
+request.headers.get('ect')
+request.headers.get('save-data')
+request.headers.get('sec-ch-form-factor');
console.log("Key "+cacheKey);
const cache = caches.default;
// Try to find a match for the request in the cache
let response = await cache.match(cacheKey);
if (!response) {
//console.log("Cache miss for "+url);
// Clone the original request to modify it for the origin fetch.
// Adding a cache buster to the url to avoid the Cloudflare cache
let originRequest = new Request(imageEngineURL+(url.search ? '&' : '?')+'cfbust='+new Date().getTime(),request);
// Add the required imgeng-inputcdn custom header to the cloned request.
originRequest.headers.set("imgeng-inputcdn", "cloudflare,1");
originRequest.headers.set("cf", {cacheTtl: 86400,cacheKey: cacheKey,cacheEverything: false, polish: false,cacheTags: ['ImageEngine']});
// Fetch the response from the predefined origin
response = await fetch(originRequest);
// Check if the response is ok to cache
event.waitUntil(cache.put(cacheKey, response.clone()));
}
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment