I have a public R2 bucket associated with my custom domain. It holds profile photos for my users. I

I have a public R2 bucket associated with my custom domain. It holds profile photos for my users. I use image resizing to get their profile photo from the r2 bucket and re-size it with query parameters.

I have a DNS CNAME for profile-photos.my-domain.com that points to the R2 bucket.

On my website, when a profile photo is to be displayed, the URL for the image looks like this:

URL 1: https://my-domain.com/resources/profile-photos/FNS-2304

Then, I have a worker that basically proxies the URL above to my profile-photos subdomain with a fetch request:

// The slug in this URL example is `FNS-2304`
const slug = c.req.param("photos-slug");
const { refresh } = c.req.query();
const refreshString = refresh ? `?refresh=${refresh}` : "";
const photoUrl = `https://profile-photos.my-domain.com/cdn-cgi/image/width=256,quality=99,format=auto/${slug}${refreshString}`;
return fetch(photoUrl, {})


So per my code above, URL 1 would query my R2 bucket like this:
https://profile-photos.my-domain.com/cdn-cgi/image/width=256,quality=99,format=auto/FNS-2304

When the user changes their profile photo, I immediately request the same URL with a unique query parameter at the end to force the R2 bucket to give me the newest version that the user just uploaded:

URL 2: https://my-domain.com/resources/profile-photos/FNS-2304?refresh=01HDQ5X4V6G1FKFNOT89WAR1SC

So per my code above, URL 2 would query my R2 bucket like this:

https://profile-photos.my-domain.com/cdn-cgi/image/width=256,quality=99,format=auto/FNS-2304?refresh=01HDQ5X4V6G1FKFNOT89WAR1SC

When the user that uploaded their new profile photo reviews their profile, they see the new photo. πŸŽ‰

However, when other people view my users profile page, they still are using URL 1 so they're not seeing the newest version 😑. It takes some unknown amount of time open (several minutes) for the new photo to become the cached version.

How can I force R2 or Cloudflare cache to immediately eliminate any old versions when a new photo is uploaded?
Was this page helpful?