blog.dopana

Back

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:

  1. Long documents with many headings
  2. Difficult to find specific content
  3. Readers waste time navigating
  4. 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:

  1. It finds a special heading (default is “Contents” or “TOC”)
  2. It analyzes all headings after that
  3. It creates a list of links to each heading
  4. It replaces the content between the TOC heading and the next heading
Markdown Documentremark-toc PluginFind TOC headingAnalyze headings afterCreate link listReplace TOC contentMarkdown with complete TOC

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-toc
bash
yarn add remark-toc
bash
pnpm add remark-toc
bash

[!TIP] remark-toc is ESM only, so ensure your project uses ES modules.

Basic Usage#

Simple Example#

Suppose you have file example.md:

And file example.js:

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))
js

Result after running:

Configuration 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)
js

Advanced Features#

Change TOC Heading#

If you want to use a different heading instead of “Contents”:

await remark()
  .use(remarkToc, {heading: 'Structure'})
  .process(file)
js

This 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)
js

Result:

1. [History](#history)

   1. [Discovery](#discovery)
   2. [Name and symbol](#name-and-symbol)

2. [Orbit](#orbit)
markdown

Limit Heading Depth#

Only include headings up to a certain depth:

await remark()
  .use(remarkToc, {maxDepth: 3})
  .process(file)
js

This 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)
js

Headings “References” and “Acknowledgments” won’t appear in the TOC.

Useful when you need prefix for security reasons:

await remark()
  .use(remarkToc, {prefix: 'user-content-'})
  .process(file)
js

Result:

* [History](#user-content-history)
  * [Discovery](#user-content-discovery)
markdown

Integration with Other Plugins#

remark-toc works well with other remark/rehype plugins:

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)
js

Full Pipeline#

Markdown Inputremark-tocremark-rehyperehype-slugrehype-autolink-headingsHTML Output

Using in Next.js#

With next.config.mjs#

With 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'}]]
        }
      }}
    />
  )
}
jsx

Using in Astro#

With astro.config.mjs#

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}]
    ]
  }
})
js

Security 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>
markdown

Result:

- [Bravo<script>alert(1)</script>](#bravoscriptalert1script)
markdown

Solution:

  • Sanitize markdown before processing
  • Use rehype-sanitize when 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)
js

Best Practices#

1. Heading Placement#

Place TOC heading in appropriate position - usually after intro:

# Title

Brief introduction...

## Contents

## Section 1
markdown

2. Reasonable Depth#

Don’t set maxDepth too deep - usually 3-4 is enough:

// Good
{maxDepth: 3}

// Too deep, TOC cluttered
{maxDepth: 6}
js

3. Skip Unnecessary Headings#

Skip headings like “References”, “Appendix”:

{skip: 'References|Appendix|Acknowledgments'}
js

4. Tight vs Loose#

  • tight: true for technical docs (compact)
  • tight: false for docs with lots of text (readable)

Comparison with Other Solutions#

Featureremark-tocManual TOCTOC Generator
AutomationYesNoYes
Auto-updatesYesNoYes
Highly customizableYesYesLimited
Remark integrationYesNoNo
MaintainedYesN/AVaries

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.

References#