cloudflare / templates

A collection of starter templates and examples for Cloudflare Workers and Pages
https://cloudflareworkers.com
MIT License
1k stars 638 forks source link

Caching finalized streamed HTML response? #20

Closed ahmed-sigmalux closed 1 year ago

ahmed-sigmalux commented 5 years ago

I'd like to cache the finalized HTML response with all the proxied script and font URLs. For a typical fetch this seems easy enough using the cache API:

https://developers.cloudflare.com/workers/reference/cache-api/

Given the HTML has been streamed and modified on the fly, however, would the standard cache.put even work?

pmeenan commented 5 years ago

cache.put works fine for streaming responses. The response that gets cached would just stream into the cache. You need to tell the worker to wait for the cache operation to complete before exiting by calling event.waitUntil(cache.put...). You'll want to clone the response that is being returned to the fetch handler and cache that.

That said, why (at least for the font CSS worker)?

The CSS is browser-specific so you'd need to shard the HTML cache by browser. The code already caches the CSS itself so the only overhead of the worker under normal operation is running the regex over the HTML as it streams through. It should be roughly as fast as if the HTML was cached post-processing.

You'd be better off caching the HTML upstream in the normal CDN cache (which is between the worker and the origin) and letting the worker continue to modify the stream on each response.

lauragift21 commented 1 year ago

Closing this issue because the initial question was addressed. Also the templates have moved over to the worker-sdk monorepo: https://github.com/cloudflare/workers-sdk/tree/main/templates.

if you're still experiencing issues feel free to open an issue there.