Skip to main content
HTMLRewriter transforms HTML documents with CSS selectors. It works with Response, string, and ArrayBuffer inputs. Bun’s implementation is based on Cloudflare’s lol-html.

Usage

A common use case is rewriting URLs in HTML content:
The rewriter replaces every image with a thumbnail of Rick Astley and wraps each <img> in a link, producing a diff like this:
Clicking any image now leads to a very famous video.

Input types

HTMLRewriter can transform HTML from several input types:
The Cloudflare Workers implementation of HTMLRewriter only supports Response objects.

Element Handlers

The on(selector, handlers) method registers handlers for HTML elements that match a CSS selector. The handlers run for each matching element during parsing:
Handlers can be asynchronous and return a Promise. Async operations block the transformation until they complete:

CSS Selector Support

The on() method supports a wide range of CSS selectors:

Element Operations

All element modification methods return the element instance, so calls can be chained:

Text Operations

Text chunks represent portions of text content and report their position in the text node:

Comment Operations

Comments support similar methods to text nodes:

Document Handlers

The onDocument(handlers) method registers handlers for events at the document level rather than within specific elements:

Response Handling

When transforming a Response:
  • The status code, headers, and other response properties are preserved
  • The body is transformed while maintaining streaming capabilities
  • Content-encoding (like gzip) is handled automatically
  • The original response body is marked as used after transformation
  • Headers are cloned to the new response

Error Handling

HTMLRewriter operations can throw errors in several cases:
  • Invalid selector syntax in on() method
  • Invalid HTML content in transformation methods
  • Stream errors when processing Response bodies
  • Memory allocation failures
  • Invalid input types (for example, passing a Symbol)
  • Body already used errors
Catch and handle these errors:

See also

You can also read the Cloudflare documentation, which this API is intended to be compatible with.