rehype-slug

Adds GitHub-style id attributes to h1–h6 headings so every section gets a stable link target.

Category
Headings & links
Maintained by
rehype team
License
MIT
Module format
ESM, default export
Install
npm install rehype-slug

What it does

rehype-slug gives every heading (h1 to h6) that has no id yet an id derived from its text, using the same algorithm as GitHub (the github-slugger package). Repeated headings get a numeric suffix, so ids stay unique within the document.

Example with a prefix

slug-prefix.mjs
import {rehype} from 'rehype'
import rehypeSlug from 'rehype-slug'

const file = await rehype()
  .data('settings', {fragment: true})
  .use(rehypeSlug, {prefix: 'docs-'})
  .process('<h1>Getting Started</h1><h2 id="custom">Kept as is</h2><h2>Ünïcode &amp; Symbols!</h2>')

console.log(String(file))
Output node slug-prefix.mjs
<h1 id="docs-getting-started">Getting Started</h1><h2 id="custom">Kept as is</h2><h2 id="docs-ünïcode--symbols">Ünïcode &#x26; Symbols!</h2>

Three details show up in this output: an existing id is kept, punctuation is removed, and non-ASCII letters such as ü are kept as they are (browsers handle them fine in fragment links).

Options

  • prefix (default ''): a string added in front of every generated id.

Typical companions

  • rehype-autolink-headings adds the clickable anchor links.
  • A table-of-contents step can read the ids.
  • If you also sanitize, read about plugin order: the default sanitize schema prefixes ids with user-content-.

See it working in the playground or read the heading links tutorial.

Official references

Facts on this page were checked against the package readme on November 11, 2026. Options not covered here are documented upstream.

Use ↑ ↓ to move, Enter to open.