Getting Started with Rehype

This page takes you from an empty folder to a working rehype pipeline. You need Node.js and npm; any current LTS release works (the examples here were run on Node.js 22).

1. Create a project

rehype is published as ES modules only, so tell Node.js that your project uses import syntax:

Terminal
mkdir my-rehype-project
cd my-rehype-project
npm init -y
npm pkg set type=module
npm install rehype rehype-format

npm pkg set type=module adds "type": "module" to package.json. Alternatively, name your files .mjs.

2. Process your first document

Create example.mjs:

format-document.mjs
import {rehype} from 'rehype'
import rehypeFormat from 'rehype-format'

const input = `<!doctype html><html lang=en><head><title>Demo</title></head>
<body><main><h1>Hello</h1><p>Formatted by <b>rehype</b>.</p></main></body></html>`

const file = await rehype().use(rehypeFormat).process(input)

console.log(String(file))

Run it with node example.mjs:

Output node format-document.mjs
<!doctype html>
<html lang="en">
  <head>
    <title>Demo</title>
  </head>
  <body>
    <main>
      <h1>Hello</h1>
      <p>Formatted by <b>rehype</b>.</p>
    </main>
  </body>
</html>

Three things happened. rehype() created a processor that already knows how to parse and serialize HTML. .use(rehypeFormat) added a plugin. .process(input) parsed the string into a syntax tree, ran the plugin, and serialized the tree back to HTML. The result is a virtual file (a VFile); String(file) gives you its contents.

Named import. rehype exports a function called rehype and has no default export, so the braces in import {rehype} from 'rehype' are required. Plugins are the other way around: they are default exports.

3. Work with fragments

By default, rehype parses input as a complete document, like a browser loading a page. A snippet such as <p>Hi</p> therefore gets wrapped in <html>, <head> and <body>. Set the fragment setting to keep snippets as snippets:

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>

Settings for the parser and serializer are passed with .data('settings', {...}), because rehype() has already added rehype-parse and rehype-stringify for you. Most examples on this site use fragment: true.

4. Chain plugins

Plugins run in the order you add them. This pipeline gives headings ids and marks external links:

hero.mjs
import {rehype} from 'rehype'
import rehypeSlug from 'rehype-slug'
import rehypeExternalLinks from 'rehype-external-links'

const file = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeSlug)
  .use(rehypeExternalLinks, {rel: ['nofollow']})
  .process('<h2>Quick start</h2><p>Read the <a href="https://unifiedjs.com">unified docs</a>.</p>')

console.log(String(file))
Output node hero.mjs
<h2 id="quick-start">Quick start</h2><p>Read the <a href="https://unifiedjs.com" rel="nofollow">unified docs</a>.</p>

Install the two plugins first with npm install rehype-slug rehype-external-links. Browse more in the plugin library.

5. Read and write files

For files on disk, the to-vfile package reads a file into a VFile that remembers its path, which makes error messages point at the right file:

process-file.mjs
import {writeFile} from 'node:fs/promises'
import {rehype} from 'rehype'
import rehypeFormat from 'rehype-format'
import {read, write} from 'to-vfile'

// Create a sample input file for this demo.
await writeFile('index.html', '<!doctype html><title>Demo</title><h1>Hi</h1>')

const file = await rehype().use(rehypeFormat).process(await read('index.html'))
file.path = 'index.formatted.html' // write next to the original
await write(file)

console.log('Wrote ' + file.path + ':\n' + String(file))
Output node process-file.mjs
Wrote index.formatted.html:
<!doctype html>
<html>
  <head>
    <title>Demo</title>
  </head>
  <body>
    <h1>Hi</h1>
  </body>
</html>

Install it with npm install to-vfile. If you only need to process files, the rehype CLI does this without any code.

6. See parse warnings

HTML parsing never fails: broken markup is repaired the way browsers repair it. You can still ask for warnings about the problems the parser found, and print them with vfile-reporter:

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 duplicate alt attribute was dropped (the first one wins) and reported. The preferUnquoted serializer setting removed quotes where HTML allows it.

Where to go next

Sources and further reading

Use ↑ ↓ to move, Enter to open.