Worker isn't serving webp format with image resizing

I’m having some issues getting my worker to return webp images when using format=auto. My worker is based off the example in the worker docs which passes the original request headers to the new image resize request. I was expecting it to pass the Accept header and return a webp if the browser supports it.

I tried using the basic image resizing route (/cdn-cgi) and it properly formats it as webp using the same params.

Here’s the code for my worker, I’ve verified that it’s receiving headers and the proper resize params. Thanks for your time!

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

// TODO check for svg format? return reg request if svg?
async function handleRequest(request) {
  const url = new URL(request.url)
  const s3Url = 'https://path-to-our-s3'
  const resizeParams = ['fit', 'width', 'height', 'quality', 'dpr', 'format']
  const options = {}

  // apply resize params to the options object
  resizeParams.forEach((name) => {
    if (url.searchParams.has(name)) {
      options[name] = url.searchParams.get(name)
    }
  })

  const hasResizeParams = Object.keys(options).length > 0

  // create the new request for the resized image
  if (hasResizeParams) {
    // remove worker route from image path
    const imagePath = url.pathname.replace('course-images/', '')
    const imageURL = new URL(imagePath, s3Url)
    const resizedImageRequest = new Request(imageURL.href, {
      headers: request.headers,
    })
    return fetch(resizedImageRequest, { cf: { image: options } })
  }

  // get the image from s3 if no resize params are present
  return fetch(request)
}

Incase anyone finds this, I managed to find a fix. You need to apply format=webp inside the worker like so

  const accept = request.headers.get('Accept')
  // use webp if supported
  if (accept.includes('image/webp')) {
    options.format = 'webp'
  }
1 Like

Ha! I was about to reply that you’d need to include the specific image mime type. Nice script, btw!