Long pages need deep links. When every heading has an id, readers can share /docs/page/#configuration and land on the right section. Two plugins handle this: rehype-slug creates ids and rehype-autolink-headings adds the clickable links.
Install
npm install rehype rehype-slug rehype-autolink-headingsIds, links and duplicates
import {rehype} from 'rehype'
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
const file = await rehype()
.data('settings', {fragment: true})
.use(rehypeSlug)
.use(rehypeAutolinkHeadings, {behavior: 'wrap'})
.process('<h2>Install</h2><h2>Install</h2><h3>Q&A: Common errors</h3>')
console.log(String(file))<h2 id="install"><a href="#install">Install</a></h2><h2 id="install-1"><a href="#install-1">Install</a></h2><h3 id="qa-common-errors"><a href="#qa-common-errors">Q&A: Common errors</a></h3>Notice three things:
- The second “Install” heading got
install-1: ids are unique within one processed file. - “Q&A: Common errors” became
qa-common-errors: lowercase, punctuation removed, spaces turned into dashes, the same algorithm GitHub uses for READMEs. - With
behavior: 'wrap', the whole heading text is the link.
Keeping existing ids and adding a prefix
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 & Symbols!</h2>')
console.log(String(file))<h1 id="docs-getting-started">Getting Started</h1><h2 id="custom">Kept as is</h2><h2 id="docs-ünïcode--symbols">Ünïcode & Symbols!</h2>Headings that already have an id keep it, so authors can pin important anchors. The prefix option avoids collisions with ids elsewhere on the page, such as navigation landmarks. Non-ASCII letters are kept, which browsers handle in fragment links.
Choosing a link style
The default behavior, prepend, inserts an empty link with aria-hidden="true" and tabindex="-1" before the heading text. It is meant to be styled as an icon that appears on hover. Because it is hidden from assistive technology and the keyboard, it adds no clutter, but it also gives those users no way to copy the link.
A more accessible pattern is a visible, labeled link after the text:
import {rehype} from 'rehype'
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
const file = await rehype()
.data('settings', {fragment: true})
.use(rehypeSlug)
.use(rehypeAutolinkHeadings, {
behavior: 'append',
properties: {className: ['anchor'], ariaLabel: 'Link to this section'},
content: {type: 'text', value: '#'}
})
.process('<h2>Configuration</h2>')
console.log(String(file))<h2 id="configuration">Configuration<a class="anchor" aria-label="Link to this section" href="#configuration">#</a></h2>Passing properties replaces the default aria-hidden and tabindex, so this link is focusable and announced as “Link to this section”. The wrap behavior is also accessible, because the heading text is the link name; it just makes headings look like links. This site uses an appended, hover-revealed # link.
Building a table of contents
After rehype-slug runs, every heading has an id, so a tiny custom plugin can collect them. This version stores the list on the file's data for your template to render:
import {visit} from 'unist-util-visit'
import {toString} from 'hast-util-to-string'
export default function rehypeCollectToc() {
return function (tree, file) {
const toc = []
visit(tree, 'element', function (node) {
if ((node.tagName === 'h2' || node.tagName === 'h3') && node.properties.id) {
toc.push({depth: Number(node.tagName[1]), id: node.properties.id, text: toString(node)})
}
})
file.data.toc = toc
}
}Use it after rehypeSlug; read file.data.toc after processing. Learn more in build your first plugin.
Watch out for sanitizing
If you sanitize untrusted content with the default schema after adding ids, every id gets the user-content- prefix, and your links break. Sanitize first, then run rehype-slug. Details are in the sanitizing tutorial.
Stable ids over time
Ids come from heading text, so editing a heading changes its anchor and breaks old links. For important sections, set an explicit id in the source, or use a plugin that supports custom ids, such as the community rehype-slug-custom-id.