rehype-autolink-headings

Adds links from headings to themselves so readers can copy a link to any section.

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

What it does

rehype-autolink-headings inserts a link pointing at each heading's own id. It does not create ids, so run rehype-slug (or another id source) first; headings without an id are skipped.

Wrap the heading text

slug-autolink.mjs
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&amp;A: Common errors</h3>')

console.log(String(file))
Output node slug-autolink.mjs
<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&#x26;A: Common errors</a></h3>

Append an accessible anchor

With prepend (the default) or append, the link is added next to the text. By default it gets aria-hidden="true" and tabindex="-1" plus an empty icon span. Supplying your own properties replaces those defaults, which lets you give the link a real accessible name:

autolink-append.mjs
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))
Output node autolink-append.mjs
<h2 id="configuration">Configuration<a class="anchor" aria-label="Link to this section" href="#configuration">#</a></h2>

Behaviors

behaviorResult
'prepend' (default)Link inserted inside the heading, before the text.
'append'Link inserted inside the heading, after the text.
'wrap'Heading content wrapped in the link.
'before' / 'after'Link inserted as a sibling of the heading; optionally grouped with group.

Other options are content, group, headingProperties, properties and test (which headings to link). See the heading links tutorial for accessibility trade-offs.

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.