Updated 2026-11-18
Sphinx JSON-LD: structured data from conf.py
Sphinx writes no structured data, and neither do Furo, the Read the Docs theme or the PyData theme. Google recommends JSON-LD for structured data (Google Search Central: structured data). On a docs site that means a TechArticle for each page, a BreadcrumbList that follows the toctree and a WebSite on the home page. Sphinx already knows all of that while it renders a page, so one event handler in conf.py is enough, with no template override and no extension to install. It works with any theme that prints metatags in its head, which the built-in themes, Furo, the Read the Docs theme and the PyData theme all do. Tested on Sphinx 9.2 with the html and dirhtml builders, on Alabaster and Furo.
1. Set html_baseurl
JSON-LD needs absolute URLs. Sphinx builds them from html_baseurl, which also turns on the canonical link:
# conf.py
project = "Example Docs"
html_baseurl = "https://docs.example.com/"
language = "en"
2. Add the handler to conf.py
import html
import json
import re
from urllib.parse import urljoin
def _text(s):
return html.unescape(re.sub(r"<[^>]+>", "", s or "")).strip()
def add_json_ld(app, pagename, templatename, context, doctree):
page_url = context.get("pageurl")
if doctree is None or not page_url:
return # genindex/search pages, or no html_baseurl
cfg = app.config
root = getattr(cfg, "root_doc", None) or cfg.master_doc
home = urljoin(cfg.html_baseurl, app.builder.get_target_uri(root))
site = {"@type": "WebSite", "name": cfg.project, "url": home}
if pagename == root:
ld = {"@context": "https://schema.org", **site}
else:
title = app.env.titles[pagename].astext()
crumbs = [{"name": cfg.project, "item": home}]
crumbs += [{"name": _text(p["title"]), "item": urljoin(page_url, p["link"])}
for p in context.get("parents", [])]
crumbs.append({"name": title})
ld = {"@context": "https://schema.org", "@graph": [
{"@type": "TechArticle", "headline": title, "url": page_url,
"inLanguage": cfg.language or "en", "isPartOf": site},
{"@type": "BreadcrumbList", "itemListElement": [
{"@type": "ListItem", "position": i, **c}
for i, c in enumerate(crumbs, 1)]}]}
data = (json.dumps(ld, ensure_ascii=False)
.replace("<", "\\u003c").replace(">", "\\u003e").replace("&", "\\u0026"))
context["metatags"] = context.get("metatags", "") + \
f'\n<script type="application/ld+json">{data}</script>'
def setup(app):
app.connect("html-page-context", add_json_ld)
Notes on what it does:
- The
html-page-contextevent runs for every HTML page just before its template is rendered. The handler appends one script tag tometatags, which themes print inside<head>. Asetup()function inconf.pyis how Sphinx lets a project hook events without writing an extension. - Escaping.
json.dumpswrites valid JSON; replacing<,>and&with Unicode escapes means a title containing</script>can't end the tag early, and the JSON still reads the same. - Titles come from
env.titlesas plain text, so inline markup like``code``in a heading doesn't leak HTML into the headline. Parent titles arrive as HTML inparents, so tags are stripped and entities decoded. - Breadcrumbs follow the toctree, the same chain Sphinx uses for its own "parents" links. Sphinx leaves the root document out of
parents, so the handler adds it as the first crumb. Parent links are relative;urljoinresolves them against the page URL, so it works for thehtmlanddirhtmlbuilders alike. The last item, the page itself, has noitem, which Google accepts. Orphan pages get Home plus the page. - Skipped pages. Generated pages (
genindex,search,py-modindex) have no doctree, and a build withouthtml_baseurlhas nopageurl; both are left alone so no page gets markup with relative URLs. - Descriptions. Sphinx has no per-page description by default. If you set them with the
.. meta::directive or sphinxext-opengraph, add the same text as"description"to theTechArticle.
On guide/install.rst under a Guide page in the toctree, the output is (shortened):
<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "TechArticle", "headline": "Install", "url": "https://docs.example.com/guide/install.html", …}, {"@type": "BreadcrumbList", "itemListElement": [{… "position": 1, "name": "Example Docs", "item": "https://docs.example.com/index.html"}, {… "position": 2, "name": "Guide", "item": "https://docs.example.com/guide/index.html"}, {… "position": 3, "name": "Install"}]}]}</script>
3. Dates, if you have them
Sphinx's html_last_updated_fmt is one date for the whole build, so don't use it as dateModified: a date that changes on every deploy says nothing. With sphinx-last-updated-by-git installed, each page's context["last_updated"] is its own last commit date; use that only if you also give it a machine-readable format.
4. Check the build
List built pages with no JSON-LD (only genindex.html, search.html and module indexes should be left):
sphinx-build -b html docs _build/html && grep -rL --include='*.html' 'application/ld+json' _build/html
Then check a few pages from different sections. The free structured data checker takes a URL or pasted markup and checks each block against the properties Google requires and recommends. Google's Rich Results Test shows how Google reads the breadcrumbs. The free site checker samples pages across a live site and shows which have no structured data, no description or no share image.
Common mistakes
- No
html_baseurlon Read the Docs. Read the Docs no longer editsconf.pyfor you. Sethtml_baseurl = os.environ.get("READTHEDOCS_CANONICAL_URL", "")(withimport os) so each version gets its own absolute URLs; an empty value skips the markup instead of writing relative URLs. - The same
TechArticlefrom two places, for example an extension and this handler. Search your built HTML forld+jsonbefore adding it. - Building JSON with string formatting around a title. Always go through
json.dumpsand the escapes above. - Markup for content that isn't on the page. Authors, ratings and versions must also be visible.
Automating it with Headlark
The handler gives every page the same generic types. Headlark's build step runs after sphinx-build on the output folder and writes what each page is missing from its content: one to three JSON-LD blocks with only properties whose values appear on the page (a how-to, an FAQ, a software application), plus missing descriptions, Open Graph tags and alt text. A type you already emit is kept as it is and never added twice, so it works alongside the code above.
Try it
Try it free for 14 days on one site and up to 500 pages, no card needed. Add your site, copy its secret key, and your next build ships with SEO.