Help with HTMLRewrite

So I’m new to Cloudflare workers and need some help figuring out the in and outs of things. I have a basic project set up that uses routes and reads the routes/URLs to provide different responses. In my example, if I’m going to [url]/[some name] it redirects to a JSON, but if we simply go to [url], a static webpage is displayed. I want my HTMLRewrite to hit once we’re in this static webpage. Now, the way I’m accessing this page is directly calling fetch([url]) as a response, but I’m wondering if there’s any way to store the resulting page so I can further call HTMLRewrite on it. I’m looking for information regarding it, or some helpful steps rather than a complete solution cause that’d defeat the purpose of playing around and trying to learn it.


If it is a static HTML Page then you can save the HTML Code inside the Worker itself as a Variable.
No need to get or store the HTML from Database or fetch it.
After this you can use then HTMLRewrite.

Here is a Example.

Another Possibility is to use Wrangler to upload a whole static Website content to cloudflare and modify the code to use HTMLRewrite.

Here is another example of how to store html static and work with it.

You will need to modify the Response and insert the static html content inside the response body.
Then use HTML Rewrite on the new Response.
As last set the Headers for the Response and return it.

Some example Code about working with the response object.

const body = JSON.stringify({ foo: “bar”, …originalBody })
response = new Response(body, response)

// Add a header using set method
response.headers.set(“foo”, “bar”)

return response

Hi. Thank you for those suggestions. I think what I want is more along the lines of the second solution that you mentioned - uploading the whole static website content. To put the project simply, I was playing around with the routes and such. Then I wanted to confirm I could do it without using routes and simply using IF conditions, which was successful I think. Now, the HTML static page that I want to load is hosted at some URL. Suppose it’s hosted by someone else at [] or something similar. Is it possible for me to call HTMLRewrite on it if I don’t have the HTML file on my local machine? And if it is possible, could you point me towards the document that I can follow?

This topic was automatically closed after 31 days. New replies are no longer allowed.