Understanding etags

I have two sets of cached resources, some in R2 some from an API we have. I want to use the etag to avoid fetching the body of each if it hasn't changed. I see an etag header on the R2 buckets but not in responses from the (cached) API response (only a Last-Modified). Is R2 generating the etag and sending it along and I need to do the same on my API, or is there a way to get CF to generate an etag based on the cached proxied API resource?
4 Replies
Viktor
Viktor4w ago
You need to send etag headers yourself. Is your API hosted on workers/pages?
const object = await env.MY_BUCKET.get(key);

if (object === null) {
return new Response("Object Not Found", { status: 404 });
}

const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);

return new Response(object.body, {
headers,
});
const object = await env.MY_BUCKET.get(key);

if (object === null) {
return new Response("Object Not Found", { status: 404 });
}

const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set("etag", object.httpEtag);

return new Response(object.body, {
headers,
});
See: https://developers.cloudflare.com/r2/api/workers/workers-api-usage/
Cloudflare Docs
Use R2 from Workers
C3 (create-cloudflare-cli) is a command-line tool designed to help you set up and deploy Workers & Pages applications to Cloudflare as fast as possible.
Matt
MattOP4w ago
It's not it's just a Fastify rest api we host and proxy thru CF. I guess my naïve question is why CF can't generate an etag based on the cached entity. Totally don't mind sending it mostly curious
Viktor
Viktor4w ago
Cloudflare needs to proxy the request to your origin API anyways, as it is not able to handle the etag by itself. So I guess the benefit wasn‘t big enough generating an own etag and storing that. Also generating them on the origin server is way more straight forward
Matt
MattOP4w ago
makes sense

Did you find this page helpful?