Comment systems, documentation sites and internal wikis often accept Markdown from users and render it as HTML. That job touches every part of the unified ecosystem at once, and getting the plugin order wrong causes either broken features or security holes. Here is a complete pipeline we tested, followed by the reasoning behind each line.
The pipeline
npm install unified remark-parse remark-gfm remark-rehype rehype-sanitize rehype-slug rehype-autolink-headings rehype-highlight rehype-external-links rehype-stringifyimport {unified} from 'unified'
import remarkParse from 'remark-parse'
import remarkGfm from 'remark-gfm'
import remarkRehype from 'remark-rehype'
import rehypeSanitize from 'rehype-sanitize'
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import rehypeHighlight from 'rehype-highlight'
import rehypeExternalLinks from 'rehype-external-links'
import rehypeStringify from 'rehype-stringify'
const markdown = `## Quick start
Hi <img src=x onerror=alert(1)> there. Install it from [npm](https://www.npmjs.com/package/rehype):
~~~js
const answer = 42
~~~
| Plugin | Job |
| - | - |
| rehype-slug | ids |
`
const file = await unified()
.use(remarkParse)
.use(remarkGfm)
.use(remarkRehype) // raw HTML in the Markdown is dropped here (no allowDangerousHtml)
.use(rehypeSanitize) // 1. clean everything that came from the author
.use(rehypeSlug) // 2. then add trusted markup
.use(rehypeAutolinkHeadings, {behavior: 'wrap'})
.use(rehypeHighlight)
.use(rehypeExternalLinks, {rel: ['nofollow', 'noopener'], target: '_blank'})
.use(rehypeStringify)
.process(markdown)
console.log(String(file))Output:
<h2 id="quick-start"><a href="#quick-start">Quick start</a></h2>
<p>Hi there. Install it from <a href="https://www.npmjs.com/package/rehype" rel="nofollow noopener" target="_blank">npm</a>:</p>
<pre><code class="hljs language-js"><span class="hljs-keyword">const</span> answer = <span class="hljs-number">42</span>
</code></pre>
<table>
<thead>
<tr>
<th>Plugin</th>
<th>Job</th>
</tr>
</thead>
<tbody>
<tr>
<td>rehype-slug</td>
<td>ids</td>
</tr>
</tbody>
</table>Step by step
Markdown side: remark-parse and remark-gfm
remark-parse turns the text into an mdast tree. remark-gfm adds GitHub Flavored Markdown: tables (visible in the output), strikethrough, task lists, footnotes and autolinks. Users expect these, so enable it for user-facing Markdown.
The bridge: remark-rehype
remark-rehype converts mdast to hast. By default it drops raw HTML found in the Markdown. That is why the <img onerror> the author typed simply vanished from the paragraph: it never became part of the HTML tree. If you want to allow some HTML in Markdown, pass allowDangerousHtml: true here, add rehype-raw right after, and rely on the next step to clean it.
Sanitize first
rehype-sanitize runs before any plugin that adds markup. Everything in the tree at this point came from the author, so this is the moment to apply the allowlist. Even with raw HTML disabled, Markdown can produce dangerous links like [click](javascript:alert(1)); sanitizing removes those href values.
Then add trusted markup
The remaining plugins add things the schema would reject or alter, which is exactly why they run afterwards:
rehype-slugadds ids. After sanitizing, they stay clean (quick-start, notuser-content-quick-start).rehype-autolink-headingsneeds those ids, so it comes afterrehype-slug.rehype-highlightaddshljs-*classes that the default schema would strip.rehype-external-linksaddstargetandrelto links to other sites. User-generated links commonly getnofollow, as here.
Serialize
rehype-stringify writes the HTML. Do not pass allowDangerousHtml to it for user content.
Is it safe to add plugins after sanitizing?
Only if those plugins are trusted and derive their output from data that is already clean. The plugins above generate ids from text, classes from a fixed vocabulary, and attributes from your configuration, so they cannot reintroduce scripts. A plugin that copies arbitrary attribute values or injects raw HTML would need to run before sanitizing instead, or be avoided.
Production checklist
- Run the pipeline on the server and store or cache the HTML; do not trust HTML sent by clients.
- Keep a Content Security Policy that blocks inline scripts as a second line of defense.
- Prefix or scope heading ids if user content is shown next to your own page elements.
- Add tests with hostile Markdown (
javascript:links, raw HTML, huge inputs) and limit input size. - Pin dependency versions and review changelogs when you upgrade, especially for sanitizer and parser packages.
Want to experiment? The playground runs the rehype half of this pipeline (sanitize, slug, autolink, external links, highlight) on HTML input.