Create Table of Contents with Remark TOC
Learn how to use remark-toc to automatically generate table of contents for markdown, making documentation more readable and navigable.
Have you ever written a long markdown document with dozens of headings and had to manually create a table of contents? Or every time you add a new heading, you have to update the list of links manually? 🤔
In this post, I’ll introduce remark-toc - a plugin that helps automatically generate table of contents (TOC) for markdown easily.
Why Do You Need a Table of Contents?#
Imagine reading a 500-page book without a table of contents. You want to find information about a specific topic, but you have to flip through every page. Very exhausting and time-consuming, right?
In technical documentation, similar problems occur:
- Long documents with many headings
- Difficult to find specific content
- Readers waste time navigating
- Manual updates are labor-intensive
remark-toc solves this problem by:
- Automation - Create TOC from existing headings
- Auto-updates - When adding/editing headings, TOC updates automatically
- Highly customizable - Configure depth, skip headings, etc.
- Easy integration - Works with unified/remark pipeline
How Does Remark-toc Work?#
Think of remark-toc as an intelligent “librarian”. When you give it a markdown document:
- It finds a special heading (default is “Contents” or “TOC”)
- It analyzes all headings after that
- It creates a list of links to each heading
- It replaces the content between the TOC heading and the next heading
Installing Remark-toc#
Prerequisites#
remark-toc is a unified/remark plugin, so you need:
- Node.js 16+
- npm or yarn
- unified or remark installed
Installation#
npm install remark-tocbashyarn add remark-tocbashpnpm add remark-tocbash[!TIP] remark-toc is ESM only, so ensure your project uses ES modules.
Basic Usage#
Simple Example#
Suppose you have file example.md:
# Pluto
Pluto is a dwarf planet in the Kuiper belt.
## Contents
## History
### Discovery
In the 1840s, Urbain Le Verrier used Newtonian mechanics to predict the position of...
### Name and symbol
The name Pluto is for the Roman god of the underworld, from a Greek epithet for Hades...
### Additional Information
Some additional information about Pluto...
## Orbit
Pluto's orbital period is about 248 years...markdownAnd file example.js:
import {remark} from 'remark'
import remarkToc from 'remark-toc'
import {read} from 'to-vfile'
const file = await remark()
.use(remarkToc)
.process(await read('example.md'))
console.log(String(file))jsResult after running:
# Pluto
Pluto is a dwarf planet in the Kuiper belt.
## Contents
* [History](#history)
* [Discovery](#discovery)
* [Name and symbol](#name-and-symbol)
* [Additional Information](#additional-information)
* [Orbit](#orbit)
## History
### Discovery
In the 1840s, Urbain Le Verrier used Newtonian mechanics to predict the position of...
### Name and symbol
The name Pluto is for the Roman god of the underworld, from a Greek epithet for Hades...
### Additional Information
Some additional information about Pluto...
## Orbit
Pluto's orbital period is about 248 years...markdownConfiguration Options#
remark-toc provides many options to customize:
await remark()
.use(remarkToc, {
heading: 'Contents', // Heading to find (default: '(table[ -]of[ -])?contents?|toc')
maxDepth: 3, // Max heading depth (default: 6)
skip: 'References', // Skip specific heading
tight: true, // Tight or loose list (default: true)
ordered: false, // Ordered or unordered list (default: false)
prefix: 'user-content-' // Prefix for links
})
.process(file)jsAdvanced Features#
Change TOC Heading#
If you want to use a different heading instead of “Contents”:
await remark()
.use(remarkToc, {heading: 'Structure'})
.process(file)jsThis will find the “Structure” heading (case-insensitive) instead of “Contents”.
Ordered List with Spacing#
Create TOC as numbered list with spacing between items:
await remark()
.use(remarkToc, {ordered: true, tight: false})
.process(file)jsResult:
1. [History](#history)
1. [Discovery](#discovery)
2. [Name and symbol](#name-and-symbol)
2. [Orbit](#orbit)markdownLimit Heading Depth#
Only include headings up to a certain depth:
await remark()
.use(remarkToc, {maxDepth: 3})
.process(file)jsThis only includes H1, H2, H3 headings in the TOC.
Skip Specific Headings#
Exclude unwanted headings from TOC:
await remark()
.use(remarkToc, {skip: 'References|Acknowledgments'})
.process(file)jsHeadings “References” and “Acknowledgments” won’t appear in the TOC.
Add Prefix to Links#
Useful when you need prefix for security reasons:
await remark()
.use(remarkToc, {prefix: 'user-content-'})
.process(file)jsResult:
* [History](#user-content-history)
* [Discovery](#user-content-discovery)markdownIntegration with Other Plugins#
remark-toc works well with other remark/rehype plugins:
With rehype-slug and rehype-autolink-headings#
To create clickable TOC in HTML:
import {remark} from 'remark'
import remarkToc from 'remark-toc'
import remarkRehype from 'remark-rehype'
import rehypeSlug from 'rehype-slug'
import rehypeAutolinkHeadings from 'rehype-autolink-headings'
import rehypeStringify from 'rehype-stringify'
await remark()
.use(remarkToc) // Create TOC
.use(remarkRehype) // Markdown → HTML
.use(rehypeSlug) // Add IDs to headings
.use(rehypeAutolinkHeadings) // Add anchor links
.use(rehypeStringify) // HTML → string
.process(file)jsFull Pipeline#
Using in Next.js#
With next.config.mjs#
import remarkToc from 'remark-toc'
import remarkGfm from 'remark-gfm'
const nextConfig = {
experimental: {
mdxRs: true,
},
mdxOptions: {
remarkPlugins: [
remarkGfm,
[remarkToc, {heading: 'Contents', maxDepth: 3}]
],
},
}
export default nextConfigjsWith MDX Component#
import remarkToc from 'remark-toc'
import {MDXRemote} from 'next-mdx-remote/rsc'
export default function Post({content}) {
return (
<MDXRemote
source={content}
options={{
mdxOptions: {
remarkPlugins: [[remarkToc, {heading: 'Contents'}]]
}
}}
/>
)
}jsxUsing in Astro#
With astro.config.mjs#
import { defineConfig } from 'astro/config'
import mdx from '@astrojs/mdx'
import remarkToc from 'remark-toc'
export default defineConfig({
integrations: [mdx()],
markdown: {
remarkPlugins: [
[remarkToc, {heading: 'Contents', maxDepth: 3}]
]
}
})jsSecurity Considerations#
[!WARNING] remark-toc copies existing nodes into the TOC, which can lead to XSS attacks if markdown contains malicious content.
Dangerous example:
## Contents
## Bravo<script>alert(1)</script>markdownResult:
- [Bravo<script>alert(1)</script>](#bravoscriptalert1script)markdownSolution:
- Sanitize markdown before processing
- Use
rehype-sanitizewhen converting to HTML - Don’t trust user input
import rehypeSanitize from 'rehype-sanitize'
await remark()
.use(remarkToc)
.use(remarkRehype)
.use(rehypeSanitize) // Sanitize HTML
.use(rehypeStringify)
.process(file)jsBest Practices#
1. Heading Placement#
Place TOC heading in appropriate position - usually after intro:
# Title
Brief introduction...
## Contents
## Section 1markdown2. Reasonable Depth#
Don’t set maxDepth too deep - usually 3-4 is enough:
// Good
{maxDepth: 3}
// Too deep, TOC cluttered
{maxDepth: 6}js3. Skip Unnecessary Headings#
Skip headings like “References”, “Appendix”:
{skip: 'References|Appendix|Acknowledgments'}js4. Tight vs Loose#
tight: truefor technical docs (compact)tight: falsefor docs with lots of text (readable)
Comparison with Other Solutions#
| Feature | remark-toc | Manual TOC | TOC Generator |
|---|---|---|---|
| Automation | Yes | No | Yes |
| Auto-updates | Yes | No | Yes |
| Highly customizable | Yes | Yes | Limited |
| Remark integration | Yes | No | No |
| Maintained | Yes | N/A | Varies |
Conclusion#
remark-toc is a useful tool for anyone writing long markdown documentation. It helps:
- Automatically create TOC from headings
- Reduce maintenance effort
- Flexible customization
- Easy integration with unified ecosystem
[!TIP] Best practice: Always use remark-toc with rehype-slug and rehype-autolink-headings for complete TOC with clickable links.