Skip to main content
Bun implements the HTMLRewriter API for parsing and transforming HTML documents using CSS selectors. It’s based on Cloudflare Workers’ HTMLRewriter and uses the lol-html parser.

Basic Usage

Selecting Elements

CSS Selectors

Use any valid CSS selector:

Multiple Selectors

Element Handlers

Element Handler

Called when an element is encountered:

Text Handler

Called for text nodes:

Comment Handler

Called for HTML comments:

Modifying Elements

Attributes

Content

Insertion

Removal

Text Manipulation

Text Nodes

Text Processing

Document Handlers

Document-Level Events

Transforming Responses

Basic Transform

Streaming Transform

Common Use Cases

Add Analytics

Lazy Load Images

Content Security

Extract Metadata

Syntax Highlighting

Localization

Performance

Streaming Benefits

HTMLRewriter processes HTML as it streams:

Memory Efficiency

Error Handling

Best Practices

  1. Use specific selectors
  2. Avoid blocking operations
  3. Minimize transformations
  4. Handle missing attributes

API Reference

HTMLRewriter

rewriter.on()

rewriter.onDocument()

rewriter.transform()

Element

Text

Platform Support

HTMLRewriter works on:
  • Bun
  • Cloudflare Workers
  • Any environment with a compatible polyfill

Differences from Cloudflare Workers

Bun’s implementation is fully compatible with Cloudflare Workers’ HTMLRewriter API.