Wordpress image resize and Webp conversion in business plan

Using the following script on Workers but it’s not working as it returns an error.
Can someone help me with this?

/** image webp conversion
/
/
*

  • Assume we have an image server able to serve webp, convert png and jpg
  • urls to webp urls if the browser supports it
    */
    addEventListener(‘fetch’, event => {
    event.respondWith(makeWebp(event.request))
    })

async function makeWebp(request) {

let regex = /\.jpg$|\.jpeg|\.png$/

if(request.headers.get('Accept')
    && request.headers.get('Accept').match(/image\/webp/)
    && request.url.match(regex)) {
    /**
     * Replace jpg / png with webp
     */
    let url = new URL(request.url.replace(regex, '.webp'))

    /**
     * Create a new request with the webp url
     */
    const modifiedRequest = new Request(url, {
        method: request.method,
        headers: request.headers
    })

    /**
     * Fetch the webp response
     */
    const webpResponse = await fetch(modifiedRequest)

    /**
     * Add webworker header to the webp response so we can
     * check live if the webworking is doing what it should do
     */
    const webpHeaders = new Headers(webpResponse.headers)
    webpHeaders.append('X-WebWorker', 'active')

    /**
     * Return a new response object
     */
    return new Response(webpResponse.body, {
        status: webpResponse.status,
        statusText: webpResponse.statusText,
        headers: webpHeaders
    })

} else {
    const response = await fetch(request)
    return response
}

}

I usually have to stumble my way through Javascript. What error are you seeing?

Maybe @sandro or @matteo can see something wrong with your code.

1 Like

I’m not immediately seeing anything obvious that would cause the code to error. Can you tell us what the error exactly was that you ran into?

Looks like this script has been posted before at Reroute image to webp when supported, and I’m also not seeing any messages there about users receiving errors with it.

If you are on a business plan why not just use Polish, and disable webp conversion on your origin?

What is your website so we can double-check?

It appears that Polish works as it should, images that benefit from being converted to webp are automatically being polished/converted by Cloudflare.

1 Like

Here are the DOCS: https://developers.cloudflare.com/images/image-resizing/resize-with-workers/

and does not work…