I am kinda new to Cloudflare’s HTMLRewriter function.
I am trying to replace a jsp tag with some html using HTMLRewriter.
More precisely, <%= "${header}" %>
. Is there a way I could possibly do this?
I managed to replace a header tag <header>
, but not jsp or some other string.
Advertisement
Answer
Unfortunately, this JSP tag is not valid HTML and so won’t be recognized as any sort of HTML element by HTMLRewriter
. Your options are probably:
- Read the whole HTML into a string and do a string replacement. This will use a lot of memory and will hurt your TTFB since the client can’t receive any bytes until the worker has received the whole file and done the replacement.
- Use the streams API to read one chunk at a time and perform the replacement. Once the replacement is complete you could use
pipeTo()
to stream through the rest of the file efficiently. The problem with this approach is that it can be very complicated to get the matching logic right. The string you are looking for could end up split across multiple chunks of the stream, so the state machine required to handle that is tricky. - Change your origin to send valid HTML like
<header></header>
instead of<%= "${header}" %>
. Based on your question I’m guessing this isn’t possible or you would have done it already. But, it’s really the cleanest option if you can find some way to do it.