Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

HTMLRewriter Streaming, Fetch Handlers, and Execution Context

How Cloudflare Workers HTMLRewriter streams replacements, how fetch handlers use ctx, and common lifecycle mistakes to avoid.

This page summarises Cloudflare Workers documentation on transforming HTML at the edge with HTMLRewriter, the HTTP fetch() handler pattern (request, env, ctx), and lifecycle APIs such as ctx.waitUntil() and ctx.passThroughOnException(). It is aimed at developers who proxy or rewrite pages in a Worker and need faster streaming replacements, background work after the response, or safe failure behaviour in front of an origin.

fetch() handler: how HTTP requests enter a Worker

Section titled “fetch() handler: how HTTP requests enter a Worker”

Incoming HTTP requests to a Worker are passed to the fetch() handler as a Request, and you answer by returning a Response.

Incoming HTTP requests to a Worker are passed to the fetch() handler as a Request object. To respond to the request with a response, return a Response object:

— Cloudflare, Fetch Handler

When a request hits your *.workers.dev subdomain or a Cloudflare-managed route, any data center invokes that handler. The third argument is ctx (execution context); the second is env (bindings such as KV, R2, or service bindings). See Handlers for other entry points (scheduled, queue, and others).

Request context: where fetch() subrequests are allowed

Section titled “Request context: where fetch() subrequests are allowed”

The Fetch API inside a Worker only runs during the Request context, which starts when fetch(request, env, ctx) runs.

Each time a Worker is invoked by an incoming HTTP request, the fetch() handler is called on your Worker. The Request context starts when the fetch() handler is called, and asynchronous tasks (such as making a subrequest using the fetch() API) can only be run inside the Request context:

— Cloudflare, Request

Calling fetch() in global scope throws. The same rule appears in Web standards: fetch() is only available inside the Request context. Incoming Request objects are immutable; clone or construct a new Request to change URL or options (Request — Immutability).

HTMLRewriter: parse and rewrite HTML on the way to the client

Section titled “HTMLRewriter: parse and rewrite HTML on the way to the client”

HTMLRewriter lets you parse and transform HTML inside a Worker—similar in spirit to DOM-style APIs, but on a streaming response from fetch().

The HTMLRewriter class allows developers to build comprehensive and expressive HTML parsers inside of a Cloudflare Workers application. It can be thought of as a jQuery-like experience directly inside of your Workers application.

— Cloudflare, HTMLRewriter

Typical flow: fetch the HTML from origin or storage, attach element handlers with .on(selector, handler), then return rewriter.transform(response) from the fetch() handler. Handlers can implement element, text, and comments; document-level hooks use .onDocument(). Async handlers may call fetch, KV, or cache before mutating nodes (Async Handlers).

Content types: string, Response, and ReadableStream

Section titled “Content types: string, Response, and ReadableStream”

Inserted content may be a string, a Response, or a ReadableStream. Optional { html: true } treats content as raw HTML; otherwise text is escaped (Global types).

Element methods include replace, append, prepend, setInnerContent, before, after, and removal helpers—each accepts that Content type (Methods).

HTMLRewriter streaming: pass a Response into replace without buffering

Section titled “HTMLRewriter streaming: pass a Response into replace without buffering”

People often look this up when edge replacement of a fragment (personalisation, i18n, SPA shell injection) used to require reading the full upstream body into a string and slowed time-to-first-byte.

You can now transform HTML elements with streamed content using HTMLRewriter. Methods like replace, append, and prepend now accept Response and ReadableStream values as Content.

— Cloudflare, Transform HTML quickly with streaming content

Now, you can pass the Response object directly into the replace method, and HTMLRewriter will immediately start replacing the content as it is streamed in. This makes responses faster.

— Cloudflare, Transform HTML quickly with streaming content

Pattern from the same changelog: fetch origin HTML, fetch upstream fragment, call element.replace(res) in an async element handler, return new HTMLRewriter().on("[data-to-replace]", handler).transform(response). Comments in the example note the upstream body is not fully buffered in memory for the replace. Full API detail remains in HTMLRewriter.

Practical uses in the cluster include localizing a website (data-i18n-key attributes rewritten per Accept-Language) and chaining handlers for SPA shell bootstrap data.

Text nodes may arrive as multiple chunks; concatenate chunks until lastInTextNode is true (Text chunks).

If a handler throws, parsing stops, the transformed body errors, and the untransformed body is canceled. If bytes were already sent, the client may see a truncated response (Errors). Plan explicit error responses instead of throwing mid-stream when possible.

Context (ctx): waitUntil and passThroughOnException

Section titled “Context (ctx): waitUntil and passThroughOnException”

The Context API manages Worker lifecycle methods. For module Workers, ctx is the third fetch() parameter (or this.ctx on WorkerEntrypoint) (Context).

ctx.waitUntil(): background work after the response

Section titled “ctx.waitUntil(): background work after the response”

ctx.waitUntil(promise) extends the invocation so work can finish after you return a Response, without blocking the client.

ctx.waitUntil() extends the lifetime of your Worker, allowing you to perform work without blocking returning a response, and that may continue after a response is returned.

— Cloudflare, Context — waitUntil

Use it for logging, analytics, or caches.default.put when the client does not need that work to complete first. If the response depends on the work, await it or stream the response as work completes. A Worker that is still streaming a response body stays active without waitUntil() (Context — waitUntil).

Topic Limit or rule
Time after response Up to 30 seconds after the response is sent or the client disconnects; shared across all waitUntil() calls on one request
Over limit Unsettled promises are canceled; warning in Workers Logs / Tail Workers
Long jobs Prefer Queues instead of relying on waitUntil()
Durable Objects Do not use waitUntil() merely to keep an object alive during normal request handling

Workers Best Practices recommend waitUntil only for work that does not affect the response, and warn that destructuring ctx (for example const { waitUntil } = ctx) causes Illegal invocation at runtime.

ctx.passThroughOnException(): fail open to the origin

Section titled “ctx.passThroughOnException(): fail open to the origin”

passThroughOnException() tells the runtime to forward the request to the origin when unhandled exceptions occur in Worker code—useful when the Worker sits in front of an existing site.

The passThroughOnException method allows a Worker to fail open ↗︎, and pass a request through to an origin server when a Worker throws an unhandled exception.

— Cloudflare, Context — passThroughOnException

It does not forward origin fetch() failures. Wrap fetch(request) in try/catch and return a 5xx when the origin fetch fails (Errors and exceptions — Go to origin on error). Bodies are streamed and not buffered: if the request body was consumed and an error happens later, pass-through cannot replay the body (Context — passThroughOnException).

Workers Best Practices advise against using passThroughOnException as everyday error handling—it hides bugs. Prefer explicit try/catch and structured error Responses.

Common mistakes when rewriting HTML at the edge

Section titled “Common mistakes when rewriting HTML at the edge”

An async call that is neither awaited nor passed to ctx.waitUntil() may be canceled when the invocation ends.

A Promise that is not awaited, returned, or passed to ctx.waitUntil() is a floating promise. Floating promises cause silent bugs: dropped results, swallowed errors, and unfinished work.

— Cloudflare, Workers Best Practices — Always await or waitUntil your Promises

Use await when the response needs the result; use ctx.waitUntil() for fire-and-forget work within the 30-second post-response window.

Proxy Workers: origin errors vs Worker exceptions

Section titled “Proxy Workers: origin errors vs Worker exceptions”

For origin proxying, enable passThroughOnException() only with a clear migration story, and still catch origin fetch errors. Uncaught logic errors may reach the origin as if the Worker were absent; origin throws after body consumption can produce confusing 4xx responses without the original body (Errors and exceptions, Context).

Assuming one text handler equals one DOM text node

Section titled “Assuming one text handler equals one DOM text node”

Relying on a single text() callback for a full sentence breaks under streaming parse; buffer until lastInTextNode (Text chunks).

  1. Reproduce the fetch() → HTMLRewriter().transform(response) pattern in the Workers Playground and confirm the response streams without loading the full upstream body when using element.replace(res) (changelog example).
  2. Add a deliberate post-response task with ctx.waitUntil() (for example a cache put) and confirm the client receives the response immediately while the task completes, per Context — waitUntil.
  3. Review Workers Logs or Tail Workers for waitUntil() tasks did not complete within the allowed time if background work exceeds the 30-second post-response limit (Context — waitUntil).
  4. For proxy setups, test both an uncaught exception in Worker code (with passThroughOnException) and a failed origin fetch with try/catch, matching Errors and exceptions.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about.