hey all I ve a question about etags
hey all, I've a question about etags & caching... I know that
cache.match()
will look at If-None-Match
and if it matches, it will return a 304
response, however if the requested URL is not cached, then cache.match()
will fail and then I'll fetch from origin.
I'm wondering what logic I should use at this point (content is not in cache BUT etag matches the content from origin) as I'd still like to return a 304
at this point. I've been looking for worker examples to do that but haven't found any to my surprise (thought it'd be a pretty common thing to do).
Any ideas?1 Reply
Hey 👋 I had a similar issue recently. 🙂
I wanted to return the 304 Not Modified response to the client as quick as possible, but at the same time I wanted to somehow force Workers to cache it with
cache.put()
.
As expected, you can't cache non-200 responses... So I created a new async function, handleModifiedResponse
, to be invoked if response.status === 304
and NOT from cache, and called it with context.waitUntil
, so it wouldn't delay the current execution.
The handleModifiedResponse
clones the request, removes the If-MOdified-Since
and If-None-Match
headers, and sends the requests to the Origin again, forcing a 200 response. And now I can cache the response with cache.put()
.
Some people might complain about hitting the Origin twice, one for the 304 and another one for the 200, but it is the best scenario in my opinion. Visitors will get their 304 (if conditions are met) real quick, and we will be able to cache any non-cached asset.