Skip to content

Instantly share code, notes, and snippets.

@vtml
Last active April 30, 2020 02:40
Show Gist options
  • Save vtml/ff3d2f566113e7b7f926c2fb2f81e747 to your computer and use it in GitHub Desktop.
Save vtml/ff3d2f566113e7b7f926c2fb2f81e747 to your computer and use it in GitHub Desktop.
CloudFlare Image Resizing Edge Worker for Sitecore
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
/**
* Fetch and log a request
* @param {Request} request
*/
async function handleRequest(request) {
// Parse request URL to get access to query string
let url = new URL(request.url);
// Cloudflare-specific options are in the cf object.
let options = { cf: { image: {} } }
options.cf.image.quality = 85;
options.cf.metadata = 'none';
options.cf.format = 'auto';
options.cf.image.fit = 'contain';
// Copy parameters from query string to request options.
// You can implement various different parameters here.
if (url.searchParams.has("w")) options.cf.image.width = url.searchParams.get("w");
if (url.searchParams.has("h")) options.cf.image.height = url.searchParams.get("h");
if (url.searchParams.has("mw")) options.cf.image.width = url.searchParams.get("mw");
if (url.searchParams.has("mh")) options.cf.image.height = url.searchParams.get("mh");
// The aspect ratio is ignored (ie. "iar" query string parameter is supplied from Sitecore Media Provider)
if (url.searchParams.has("iar")) options.cf.image.fit = 'cover'
// Forwarding the request to Sitecore Content Delivery, using only the Revision ID as a query string parameter if supplied
const originHost = 'https://content-delivery.example.com';
let imagePath = url.pathname;
if (url.searchParams.has("rev")) imagePath += '?rev=' + url.searchParams.get("rev")
const originUrl = new URL(imagePath, originHost);
// Build a request that passes through request headers,
// so that automatic format negotiation can work.
const imageRequest = new Request(originUrl.toString(), {
headers: request.headers,
});
// Returning fetch() with resizing options will pass through response with the resized image.
return fetch(imageRequest, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment