Cloudflare Images Domain

Would it be possible to add a custom domain for the images instead of the default one.

This is on the roadmap but isn’t a native feature at this time. You can use a Worker for now though to do this.

2 Likes

Interesting!
Could you expand a bit about how to use a worker to replace a domain?
Thanks.

It’d be similar to this:

1 Like

Of course!

So, let’s assume you map this Worker to something like cdn.example.com/* you can then fetch the Images URL. We can make this a little prettier too by having the account ID in the Worker rather than in the request URL
Something like this:

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

// You can find this in the dashboard, it should look something like this: ZWd9g1K7eljCn_KDTu_MWA
const accountHash = '';

async function handleRequest(request) {
  const { pathname } = new URL(request.url);
  // A request to something like cdn.example.com/c92fee06-0877-47ff-9aaa-501d3dcd5600/profile
  // will fetch "https://imagedelivery.net/<accountHash>/c92fee06-0877-47ff-9aaa-501d3dcd5600/profile"
  return fetch(`https://imagedelivery.net/${accountHash}${pathname}`);
}

An example of this in the docs might be nice though I’d need to check if it’d be ok to do

3 Likes

Thanks!

1 Like

@Walshy’s code is what I’d go with. He either had it laying around, or just spouted it off the top of his head. Either way, it’s a good choice.

I thought it was account hash not account id https://developers.cloudflare.com/images/serving-images ?

Yes it is, it’s made up from the account ID. Just couldn’t remember what the official name for it was. I thought I had included mine in the code to show it was that but apparently not

1 Like

That seems like very useful code!
I like the idea of using the worker to change the url a bit. For example you could switch the position of the variant and the file id so it looks like folder/file instead of file/variant. Could even add an extension suffix (.jpg) and later remove and ignore it.
Haven’t used workers myself yet, but reading the docs it seems we could save the list of images in a KV set, and have the worker pull the image id by requesting the original file name in the url.

In the end, I hope CF give us those features without the need of coding a worker.

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