Rehype Parse and Stringify Explained

The parser and serializer at the heart of rehype: fragments, parse errors, and the options that change the output.

Every rehype pipeline starts with rehype-parse and, if it outputs HTML, ends with rehype-stringify. The rehype package includes both. Understanding their options lets you control exactly what comes in and what goes out.

rehype-parse: HTML to hast

rehype-parse follows the WHATWG HTML standard, so it never throws on bad markup. It repairs it the way a browser does:

unified-explicit.mjs
import {unified} from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeStringify from 'rehype-stringify'

const file = await unified()
  .use(rehypeParse, {fragment: true})
  .use(rehypeStringify)
  .process('<p>Unclosed <em>emphasis<p>Second paragraph')

console.log(String(file))
Output node unified-explicit.mjs
<p>Unclosed <em>emphasis</em></p><p><em>Second paragraph</em></p>

The second paragraph is wrapped in <em> too. That surprises people, but it is exactly what browsers do with an unclosed formatting element (the “adoption agency” rules). Parsing with rehype tells you what the browser will actually render.

Fragments versus documents

The most important parser option is fragment. By default it is false, and missing <html>, <head> and <body> elements are added. With fragment: true, the input is treated as a snippet:

fragment-vs-document.mjs
import {rehype} from 'rehype'

const input = '<p>Just a paragraph</p>'

const asDocument = await rehype().process(input)
const asFragment = await rehype().data('settings', {fragment: true}).process(input)

console.log('document:', String(asDocument))
console.log('fragment:', String(asFragment))
Output node fragment-vs-document.mjs
document: <html><head></head><body><p>Just a paragraph</p></body></html>
fragment: <p>Just a paragraph</p>

Reporting parse errors

Set emitParseErrors: true to get warnings for each problem the parser fixed, with positions. They are messages on the file, not exceptions:

settings-warnings.mjs
import {rehype} from 'rehype'
import {reporter} from 'vfile-reporter'

const file = await rehype()
  .data('settings', {emitParseErrors: true, fragment: true, preferUnquoted: true})
  .process('<img src="cat.png" alt="A cat" alt="Duplicate">')

console.log(String(file))
console.log(reporter(file))
Output node settings-warnings.mjs
<img src=cat.png alt="A cat">
1:35-1:35 warning Unexpected duplicate attribute duplicate-attribute hast-util-from-html

⚠ 1 warning

The readme lists every parse error by name, and you can turn individual ones off.

rehype-stringify: hast to HTML

rehype-stringify uses hast-util-to-html. Its defaults produce conventional HTML: double-quoted attributes, no self-closing slashes, and characters encoded only when needed. Options change that:

stringify-options.mjs
import {rehype} from 'rehype'

const input = '<img src="logo.svg" alt="Logo"><input type="checkbox" checked>'

const plain = await rehype().data('settings', {fragment: true}).process(input)

const custom = await rehype()
  .data('settings', {fragment: true, closeSelfClosing: true, preferUnquoted: true})
  .process(input)

console.log('default:', String(plain))
console.log('custom: ', String(custom))
Output node stringify-options.mjs
default: <img src="logo.svg" alt="Logo"><input type="checkbox" checked>
custom:  <img src=logo.svg alt=Logo /><input type=checkbox checked />

Some options worth knowing:

OptionEffect
closeSelfClosingWrite <img /> instead of <img> for void elements.
preferUnquotedLeave attribute values unquoted when HTML allows it.
quote / quoteSmartChoose " or ', or pick whichever needs less escaping.
omitOptionalTagsDrop tags HTML lets you omit, such as </p>.
characterReferencesHow characters are encoded (shortest, decimal, named).
allowDangerousHtmlOutput raw nodes as-is (dangerous with untrusted content).

The minify preset is mostly a collection of these settings plus tree transforms; see format and minify HTML.

Passing options

When you use the rehype package, the parser and serializer are already attached, so options go through .data('settings', …), as in the examples above. When you build the processor yourself with unified, pass options directly:

JS
unified()
  .use(rehypeParse, {fragment: true})
  .use(rehypeStringify, {closeSelfClosing: true})

When to use only one of them

  • Only rehype-parse: HTML in, something else out, such as Markdown via rehype-remark, or analysis of the tree.
  • Only rehype-stringify: something else in, HTML out, such as Markdown via remark-rehype.

Sources and further reading

Use ↑ ↓ to move, Enter to open.