Skip to main content
HTMLRewriter lets you use CSS selectors to transform HTML documents. It works with Request, Response, as well as string. Bun’s implementation is based on Cloudflare’s lol-html.

Usage

A common usecase is rewriting URLs in HTML content. Here’s an example that rewrites image sources and link URLs to use a CDN domain:
This replaces all images with a thumbnail of Rick Astley and wraps each <img> in a link, producing a diff like this:
Now every image on the page will be replaced with a thumbnail of Rick Astley, and clicking any image will lead to a very famous video.

Input types

HTMLRewriter can transform HTML from various sources. The input is automatically handled based on its type:
Note that Cloudflare Workers implementation of HTMLRewriter only supports Response objects.

Element Handlers

The on(selector, handlers) method allows you to register handlers for HTML elements that match a CSS selector. The handlers are called for each matching element during parsing:
The handlers can be asynchronous and return a Promise. Note that async operations will block the transformation until they complete:

CSS Selector Support

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

Element Operations

Elements provide various methods for manipulation. All modification methods return the element instance for chaining:

Text Operations

Text handlers provide methods for text manipulation. Text chunks represent portions of text content and provide information about their position in the text node:

Comment Operations

Comment handlers allow comment manipulation with similar methods to text nodes:

Document Handlers

The onDocument(handlers) method allows you to handle document-level events. These handlers are called for events that occur 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 (e.g., passing Symbol)
  • Body already used errors
Errors should be caught and handled appropriately:

See also

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