A Markdown table of contents is one of those things that is right on the day you write it and wrong a month later: a heading gets renamed, a section moves, and the link at the top of the README now goes nowhere. The fix is to generate the list from the headings and let tooling keep it current. This guide covers how GitHub builds heading anchors, two maintained generators (doctoc and remark-toc), a small dependency-free Node.js script with a check mode, pre-commit and lint-staged hooks, a GitHub Actions job that fails when a TOC is stale, and the built-in options in MkDocs, Python-Markdown and Hugo.

From my own work: On documentation repositories I maintain, broken TOC links were a steady source of small issues and pull requests, almost always from a renamed heading. After adding a generator to the pre-commit hook and a check to CI, that category of issue stopped. The setup took less time than fixing the links by hand had taken in a single month.
How GitHub turns headings into anchors
Every TOC link points at an anchor that the renderer generates from the heading text. GitHub documents its rules (GitHub Docs: section links):
- Letters are converted to lower case.
- Spaces become hyphens; other whitespace and punctuation are removed.
- Leading and trailing whitespace is removed.
- Markup is removed, so
_italics_becomesitalics. - A duplicate anchor gets a hyphen and an incrementing number:
#faq, then#faq-1.
## Getting Started -> #getting-started
## Install `my-cli` -> #install-my-cli
## What's New in v2.0? -> #whats-new-in-v20
## FAQ -> #faq
## FAQ -> #faq-1
GitLab, Bitbucket and static site generators use similar but not identical rules, especially for non-Latin characters and duplicate headings. That is why generators have a mode flag for each platform, and why you should generate the TOC for the place where people actually read the file.
Also note that GitHub already shows an outline menu for rendered Markdown files with headings. An in-file table of contents is still worth having: it shows up in editors, in package registries that render the README, in printed or exported docs, and on sites that do not provide an outline.
Markdown table of contents tools compared
| Tool | How it finds the TOC | Best for |
|---|---|---|
| doctoc | <!-- START doctoc --> and <!-- END doctoc --> comments |
READMEs and docs folders, CI check with --dryrun |
| remark-toc | A heading named Contents, Table of contents or TOC | Projects already using remark or MDX |
| markdown-toc | <!-- toc --> and <!-- tocstop --> comments |
Older Node projects already using it |
| Custom script (below) | The same toc comments |
Full control, no dependencies |
| MkDocs, Python-Markdown, Hugo | Generated at build time from headings | Documentation sites |
| Editor extensions | Command in the editor | Personal notes; not enforceable in CI |
doctoc: the quickest route for a README
doctoc inserts or updates a TOC between comment markers and supports GitHub, GitLab, Bitbucket and other anchor styles (doctoc). The first run adds the markers for you.
npm install --save-dev doctoc
# add or update the TOC in one file
npx doctoc README.md --github
# every .md, .markdown and .mdx file under docs/ (skips .git and node_modules)
npx doctoc docs --github
# only headings from ## to ###, and a custom title
npx doctoc README.md --github --minlevel 2 --maxlevel 3 --title '**Contents**'
# CI: change nothing, exit 1 if any TOC is out of date
npx doctoc README.md docs --github --dryrun
After the first run the README contains a block like this, which you can move anywhere in the file; later runs update it in place:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
**Contents**
- [Getting Started](#getting-started)
- [Install my-cli](#install-my-cli)
- [Configuration](#configuration)
- [FAQ](#faq)
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
Useful options: --update-only (-u) touches only files that already have a TOC, which is what you want in hooks; --notitle removes the title; --gitlab or --bitbucket switch the anchor style; --mintocitems skips the TOC for short files.
remark-toc: when you already use remark or MDX
remark-toc looks for a heading that matches (table[ -]of[ -])?contents?|toc, case-insensitive, and replaces everything under it up to the next heading of the same or higher level with the generated list. Options include heading, maxDepth, tight and ordered (remark-toc).
npm install --save-dev remark-cli remark-toc
# rewrite README.md in place
npx remark README.md --use remark-toc --output
// .remarkrc.mjs - shared settings for the CLI and editor integrations
import remarkToc from 'remark-toc';
export default {
plugins: [[remarkToc, { heading: 'contents', maxDepth: 3, tight: true }]],
};
remark parses the whole file and writes it back, so it also normalises formatting such as list markers and emphasis style. That is good if you want consistent Markdown everywhere, but the first run can produce a large diff. Commit that formatting change on its own before turning on the check.
A no-dependency Markdown table of contents script
If you want no new packages, or need rules a generator does not offer, about 80 lines of Node.js are enough. This script reads the files you pass, skips fenced code blocks, lists ## and ### headings that appear below the markers, follows GitHub’s anchor rules including duplicates, and has a --check mode for CI. It uses the same <!-- toc --> markers as markdown-toc, so you can switch between them.
// scripts/toc.mjs (Node.js 20+, no dependencies)
// Usage: node scripts/toc.mjs [--check] README.md docs/*.md
import { readFileSync, writeFileSync } from 'node:fs';
const START = '<!-- toc -->';
const END = '<!-- tocstop -->';
const MIN = 2, MAX = 3; // include ## and ### headings
const args = process.argv.slice(2);
const check = args.includes('--check');
const files = args.filter((a) => a !== '--check');
// Close to GitHub's rules: lower-case, drop punctuation, spaces to hyphens
function slugify(text) {
return text.trim().toLowerCase()
.replace(/[^p{L}p{M}p{N}p{Pc} -]/gu, '')
.replace(/ /g, '-');
}
// Remove inline Markdown so the TOC shows plain heading text
function plain(text) {
return text
.replace(/!?[([^]]*)]([^)]*)/g, '$1') // links and images
.replace(/`([^`]*)`/g, '$1') // inline code
.replace(/(**|__|*|_|~~)(.+?)1/g, '$2') // emphasis
.replace(/<[^>]+>/g, '') // inline HTML
.trim();
}
function buildToc(markdown) {
const seen = new Map();
const lines = [];
let fence = null;
let afterToc = false;
for (const line of markdown.split('n')) {
const f = line.match(/^s*(`{3,}|~{3,})/);
if (f) {
if (!fence) fence = f[1][0];
else if (f[1][0] === fence) fence = null;
continue;
}
if (fence) continue;
if (line.trim() === END) { afterToc = true; continue; }
const h = line.match(/^(#{1,6})s+(.+?)s*#*s*$/);
if (!h) continue;
const level = h[1].length;
const text = plain(h[2]);
let slug = slugify(text);
const n = seen.get(slug) || 0; // duplicates get -1, -2 ...
seen.set(slug, n + 1);
if (n) slug = `${slug}-${n}`;
if (!afterToc || level < MIN || level > MAX) continue; // list headings below the TOC
lines.push(`${' '.repeat(level - MIN)}- [${text}](#${slug})`);
}
return lines.join('n');
}
let stale = 0;
for (const file of files) {
const src = readFileSync(file, 'utf8');
const a = src.indexOf(START);
const b = src.indexOf(END);
if (a === -1 || b === -1 || b < a) continue; // no markers: leave the file alone
const out = src.slice(0, a + START.length) + 'nn' + buildToc(src) + 'nn' + src.slice(b);
if (out === src) continue;
stale++;
if (check) console.error(`TOC out of date: ${file}`);
else { writeFileSync(file, out); console.log(`updated ${file}`); }
}
if (check && stale) process.exit(1);
<!-- in README.md, once -->
## Contents
<!-- toc -->
<!-- tocstop -->
node scripts/toc.mjs README.md docs/*.md # write
node scripts/toc.mjs --check README.md docs/*.md # exit 1 if stale
The slug function covers GitHub’s documented rules and Unicode letters. It does not replicate every edge case of GitHub’s renderer, such as emoji shortcodes or headings that contain raw HTML anchors; if your docs use those, prefer doctoc, which has handled GitHub anchors for years. The check mode is what makes it safe either way: a stale or wrong TOC fails before it is merged.
Update the TOC automatically before each commit
Generating in a hook means nobody has to remember. With the pre-commit framework, doctoc ships its own hook definition:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/thlorenz/doctoc
rev: v2.5.0
hooks:
- id: doctoc
args: [--github, --update-only]
In a JavaScript project, husky with lint-staged does the same for staged Markdown files only:
npm install --save-dev husky lint-staged
npx husky init
echo "npx lint-staged" > .husky/pre-commit
{
"lint-staged": {
"*.{md,mdx}": "doctoc --github --update-only"
}
}
lint-staged adds the files modified by the command back to the commit, so the updated TOC is included automatically. With the custom script, use "*.md": "node scripts/toc.mjs" instead.
Fail CI when a Markdown table of contents is stale
Hooks can be skipped, and contributors editing on the GitHub website never run them. A CI check closes that gap:
# .github/workflows/docs.yml
name: docs
on:
pull_request:
paths: ['**/*.md', '**/*.mdx']
permissions:
contents: read
jobs:
toc:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
- name: Check tables of contents
run: npx --yes doctoc@2.5.0 README.md docs --github --update-only --dryrun
# or, with the custom script:
# - run: node scripts/toc.mjs --check README.md docs/*.md
When it fails, the fix is one command the contributor can run locally. Put that command in CONTRIBUTING.md, as described in the contributor-friendly open source guide, so the failure explains itself.
Documentation sites: let the generator do it
If your Markdown is published through a static site generator, the TOC is usually generated at build time and you do not need it in the source at all:
- Python-Markdown and MkDocs: the
tocextension replaces a[TOC]marker with a nested list and addsidattributes to headings;toc_depthlimits levels andpermalinkadds a link symbol after each heading (Python-Markdown: toc). MkDocs themes use the same extension for the page sidebar. - Hugo: templates can call
.TableOfContentsto render the page’s headings, configured undermarkup.tableOfContentswithstartLevelandendLevel. - MDX-based sites such as Docusaurus, Nextra and Astro collect headings at build time and render an On this page list. The Nextra and MDX docs portal guide shows one setup.
# mkdocs.yml
markdown_extensions:
- toc:
permalink: true
toc_depth: 2-3
Tables of contents on blog posts and SEO
On a published page, a table of contents is a navigation aid, and that is how to judge it. It helps readers jump to the part they need, and stable heading IDs give you linkable sections to share or reference. Google can show jump links to sections of a page in some results, but there is no guarantee and no special markup that forces it. Write headings that describe the section clearly, keep IDs stable once published, and use plain HTML links, which also helps with the structure advice in the featured snippets guide and the semantic HTML and accessibility guide.
Keep the TOC itself accessible: wrap it in a <nav aria-label="Contents"> on websites, use a real list, and do not hide it behind a script that runs only after user interaction.
Markdown table of contents checklist
- Generated from headings, never typed by hand.
- Anchor style matched to where the file is read: GitHub, GitLab or your site.
- Only
##and###levels in long documents, to keep the list short. - Updated in a pre-commit or lint-staged hook.
- Checked in CI with
doctoc --dryrunor--check. - Built by the site generator for documentation sites instead of committed to source.
Want this done on your own server or site?
I am Saizul Amin, a web developer and technical SEO consultant. I set up and harden VPS servers, migrate WordPress sites, fix indexing problems and build automations. See my portfolio or get in touch.
FAQ
How do I add a table of contents to a Markdown file?
Add a generator such as doctoc and run it on the file, for example npx doctoc README.md –github. It inserts a list of links to every heading between comment markers and updates it on later runs.
Does GitHub generate a table of contents automatically?
GitHub shows an outline menu for rendered Markdown files with headings, but it does not insert a table of contents into the file. Add one with a generator if you want it inside the README itself.
How are Markdown heading anchors created on GitHub?
GitHub lower-cases the heading text, removes punctuation, replaces spaces with hyphens and appends -1, -2 and so on to duplicates. For example, What is New? becomes #what-is-new.
How do I keep the table of contents up to date?
Run the generator in a pre-commit hook, for example doctoc with –update-only through pre-commit or lint-staged, and add a CI step with doctoc –dryrun that fails when any TOC is out of date.
Why do my Markdown TOC links not work?
The anchors probably follow a different platform rule than the generator used, or a heading was renamed after the TOC was created. Regenerate with the correct mode, such as –github or –gitlab, and add a CI check.
Sources
- GitHub Docs: Basic writing and formatting syntax (section links)
- doctoc on GitHub
- remark-toc on GitHub
- Python-Markdown: Table of Contents extension
- pre-commit

Saizul Amin is an AI agent developer, AI automation engineer and full-stack software developer from Dhaka, Bangladesh. He builds any kind of AI agent, AI automation and custom software for any business. Portfolio: https://saizul.com

