Image Transformation via Worker get error 404/500

I can manually do Image transform via URL with:
https://ZONE/cdn-cgi/image/OPTIONS/SOURCE-IMAGE

But when I go with automatically via workers, I got stuck.
I already add routes to the image server in my zone.

Anyone has successful setup Image Transform via Worker (img is locate outside Cloudflare Images) please help.

Thanks a lot.

This is my worker.js:

async function handleRequest(request) {
  let url = new URL(request.url);
  console.log('Original request URL:', url.href); // Log the original request URL

  // Check if the request is for an image file on your domain
  if (url.hostname === "oxalisadventure.com" && 
      (url.pathname.endsWith(".jpg") || url.pathname.endsWith(".png") || url.pathname.endsWith(".webp"))) {
    
    // Construct the Cloudflare Image Optimization URL
    let imageUrl = `https://oxalisadventure.com/cdn-cgi/image/fit=scale-down,quality=60,format=auto,f=auto${url.pathname}`;
    console.log('Constructed image URL:', imageUrl); // Log the constructed image URL

    // Fetch the optimized image
    return fetch(imageUrl, request); 
  } else {
    // For non-image requests or different domains, pass through
    return fetch(request);
  }
}

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

This is worker logs:

{
  "outcome": "ok",
  "scriptVersion": {
    "id": "580556a1-7c8f-452d-a838-12f045648b69"
  },
  "scriptName": "img-optimize",
  "diagnosticsChannelEvents": [],
  "exceptions": [],
  "logs": [
    {
      "message": [
        "Original request URL:",
        "https://oxalisadventure.com/uploads/2019/09/hinh-6__637050075771493631.jpg"
      ],
      "level": "log",
      "timestamp": 1718770792252
    },
    {
      "message": [
        "Constructed image URL:",
        "https://oxalisadventure.com/cdn-cgi/image/fit=scale-down,quality=60,format=auto,f=auto/uploads/2019/09/hinh-6__637050075771493631.jpg"
      ],
      "level": "log",
      "timestamp": 1718770792252
    }
  ],
  "eventTimestamp": 1718770792245,
  "event": {
    "request": {
      "url": "https://oxalisadventure.com/uploads/2019/09/hinh-6__637050075771493631.jpg",
      "method": "GET",
      "headers": {
        "accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8",
        "accept-encoding": "gzip, br",
        "accept-language": "vi",
        "cache-control": "no-cache",
        "cf-connecting-ip": "113.162.162.92",
        "cf-ipcountry": "VN",
        "cf-ray": "8960b92b592b1fa4",
        "cf-visitor": "{\"scheme\":\"https\"}",
        "connection": "Keep-Alive",
        "cookie": "REDACTED",
        "host": "oxalisadventure.com",
        "pragma": "no-cache",
        "priority": "i",
        "referer": "https://oxalisadventure.com/",
        "sec-ch-ua": "\"Not/A)Brand\";v=\"8\", \"Chromium\";v=\"126\", \"Microsoft Edge\";v=\"126\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "image",
        "sec-fetch-mode": "no-cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0",
        "x-forwarded-proto": "https",
        "x-real-ip": "113.162.162.92"
      },
      "cf": {
        "longitude": "106.62570",
        "latitude": "10.82200",
        "tlsCipher": "AEAD-AES128-GCM-SHA256",
        "continent": "AS",
        "asn": 45899,
        "clientAcceptEncoding": "gzip, deflate, br, zstd",
        "country": "VN",
        "tlsClientAuth": {
          "certIssuerDNLegacy": "",
          "certIssuerSKI": "",
          "certSubjectDNRFC2253": "",
          "certSubjectDNLegacy": "",
          "certFingerprintSHA256": "",
          "certNotBefore": "",
          "certSKI": "",
          "certSerial": "",
          "certIssuerDN": "",
          "certVerified": "NONE",
          "certNotAfter": "",
          "certSubjectDN": "",
          "certPresented": "0",
          "certRevoked": "0",
          "certIssuerSerial": "",
          "certIssuerDNRFC2253": "",
          "certFingerprintSHA1": ""
        },
        "verifiedBotCategory": "",
        "tlsExportedAuthenticator": {
          "clientFinished": "4b61d62f5c7d1a8747f783c378c52a94961c5dbf6bf9249a62dad03bbc71565c",
          "clientHandshake": "8a2fe020e4452772a07ab151b20de6941891bac8ee2b2d7a8d3eeebaaac6bb92",
          "serverHandshake": "58f4a027e1fe1ce97ad0ce942b0ffc97444e1ee30f8c2d86eb610814b28ffbfe",
          "serverFinished": "996c85ec5f3b02a62630c537cb3e7378343b7a8eb652480302ad7e535a8e9a79"
        },
        "tlsVersion": "TLSv1.3",
        "colo": "HKG",
        "timezone": "Asia/Ho_Chi_Minh",
        "tlsClientHelloLength": "2022",
        "edgeRequestKeepAliveStatus": 1,
        "requestPriority": "",
        "tlsClientExtensionsSha1": "UWoSwGXaOF9Y9jcneMHvm8R2zeY=",
        "region": "Ho Chi Minh",
        "city": "Ho Chi Minh City",
        "regionCode": "SG",
        "asOrganization": "VNPT",
        "tlsClientRandom": "54uiKTr3vdl9qGHLMyjvdEbN/3HwsqsF94g8ONso79c=",
        "httpProtocol": "HTTP/3"
      }
    },
    "response": {
      "status": 404
    }
  },
  "id": 18
}

Hi there,

You can’t use the /cdn-cgi/image/<config>/<url> endpoint with workers, try and use cf.image request properties.

fetch(imageURL, {
  cf: {
    image: {
      fit: "scale-down",
      width: 800,
      height: 600
    }
  }
})

Take care.

Thanks a lot.

I change to use cf.image and it works now.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.