Generating Breadcrumb Structured Data in Astro
Breadcrumbs do two jobs on a content site. On the page, they tell a reader where they are and give them a one-click way up. In search results, BreadcrumbList structured data lets the search engine show a readable path — Docs › Guides › Deploying — instead of the raw URL. Both jobs are easy to get mostly right and slightly wrong: crumbs named after slugs (Getting-started), JSON-LD that disagrees with the visible trail, intermediate levels that link to pages that do not exist, and absolute URLs built with the wrong host on preview deploys.
This guide builds breadcrumbs for a 1,300-page Astro 5 documentation site with nested folders, generating the visible trail and the JSON-LD from one function, using titles from content collections, and testing both in CI. It belongs to Technical SEO for Static Sites; the general approach to structured data is in Adding JSON-LD Structured Data at Build Time.
Prerequisites
- An Astro 5 site with
siteset inastro.config.mjs, so absolute URLs can be built. - Content in collections whose IDs follow the URL structure, with an index page per folder (
guides/index.md). - A layout component every page uses, where the breadcrumb component can go.
Step 1: One Function That Builds the Trail
The trail is built from the page's URL path, with a title for each level looked up from the docs collection:
// src/lib/breadcrumbs.ts
import { getCollection } from 'astro:content';
export type Crumb = { name: string; url: URL };
const docs = await getCollection('docs');
const titleById = new Map(docs.map((d) => [d.id.replace(/\/index$/, ''), d.data.navTitle ?? d.data.title]));
export function breadcrumbs(pathname: string, site: URL, current?: string): Crumb[] {
const parts = pathname.replace(/^\/|\/$/g, '').split('/').filter(Boolean);
const crumbs: Crumb[] = [{ name: 'Home', url: new URL('/', site) }];
parts.forEach((_, i) => {
const id = parts.slice(0, i + 1).join('/');
const name = i === parts.length - 1 && current ? current : titleById.get(id);
if (name) crumbs.push({ name, url: new URL(`/${id}/`, site) });
});
return crumbs;
}
Levels without a page (no title in the map) are skipped rather than linked, so the trail never points at a 404. navTitle lets a long page title like "Deploying Astro to Cloudflare Workers Static Assets" appear as "Cloudflare Workers" in the trail.
Step 2: The Visible Trail
---
// src/components/Breadcrumbs.astro
import { breadcrumbs } from '../lib/breadcrumbs';
const { title } = Astro.props;
const trail = breadcrumbs(Astro.url.pathname, Astro.site!, title);
---
<nav aria-label="Breadcrumb">
<ol class="crumbs">
{trail.map((c, i) => (
<li>
{i < trail.length - 1
? <a href={c.url.pathname}>{c.name}</a>
: <span aria-current="page">{c.name}</span>}
</li>
))}
</ol>
</nav>
Links use the path only, so they work on preview deploys whatever the host. The current page is text with aria-current="page", and the separators are drawn in CSS (li + li::before { content: '›'; }) so screen readers do not read them as content.
Step 3: The JSON-LD
---
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: trail.map((c, i) => ({ '@type': 'ListItem', position: i + 1, name: c.name, item: c.url.href })),
};
---
<script type="application/ld+json" set:html={JSON.stringify(jsonLd)} />
item uses the absolute URL from Astro.site, which is always the production host, so preview deploys emit production URLs in structured data — correct, since only production pages are indexed. set:html with JSON.stringify escapes the content safely; building the JSON by string concatenation is how quotes in titles break structured data.
Step 4: Edge Cases
Three cases needed handling on this site:
- Pages under a version prefix (
/v2/guides/...). The version became its own crumb ("Version 2") with a link to that version's home, because it is meaningful to readers. - Localised pages (
/de/...). The language prefix is not a crumb; the function strips it and looks up titles in the localised entries, so a German page's trail is in German. - Generated API pages with no collection entry. Their titles come from the page props instead, passed as
current, and their parent folder (/api/) has an index page so the trail is complete.
Step 5: Test in CI
Two checks run against the built site. The first parses every page's JSON-LD and visible trail and asserts they match and that every crumb URL exists in the build:
for (const file of htmlFiles) {
const $ = cheerio.load(await fs.readFile(file, 'utf8'));
const ld = JSON.parse($('script[type="application/ld+json"]').filter((_, s) => $(s).text().includes('BreadcrumbList')).text());
const visible = $('nav[aria-label="Breadcrumb"] li').map((_, li) => $(li).text().trim()).get();
const names = ld.itemListElement.map((i) => i.name);
if (names.join('|') !== visible.join('|')) fail(file, 'JSON-LD and visible trail differ');
for (const i of ld.itemListElement) if (!builtPaths.has(new URL(i.item).pathname)) fail(file, `crumb ${i.item} not built`);
}
The second validates a sample of pages against schema.org definitions, as in Testing Structured Data and Meta Tags. Together they take 6 seconds on 1,300 pages.
Styling and Mobile Behaviour
Long trails wrap badly on narrow screens. On phones the component shows only the parent crumb as a back link ("‹ Guides"), with the full trail kept in the HTML and in the JSON-LD; CSS hides the middle items below 40em rather than removing them, so screen readers and search engines still see the complete path. Each crumb has a minimum tap target of 44 by 44 pixels through padding, which an accessibility audit had flagged on the old trail. The separators use the muted text colour at 4.6:1 contrast, the same token as other secondary text, so the trail stays readable in both themes.
Breadcrumb names also double as a check on the information architecture. Listing every distinct trail on the site — 212 of them — showed eleven sections whose navTitle repeated the parent's name ("Guides › Deployment guides"), which the writers shortened, and four pages filed under a folder that no longer matched their topic, which were moved with redirects.
Measured Impact
The previous implementation built crumbs from URL segments with title-cased slugs and hand-written JSON-LD in some layouts:
| Measure | Before | After | Tool |
|---|---|---|---|
| Pages with BreadcrumbList | 610 of 1,300 | 1,300 | CI check |
| Crumbs named from slugs | 2,140 | 0 | CI check |
| Crumbs linking to missing pages | 87 | 0 | CI check |
| JSON-LD/visible mismatches | 410 pages | 0 | CI check |
| Valid breadcrumb items (Search Console) | 610 pages | 1,296 pages | Enhancements report |
| CTR, pages showing breadcrumb path | 3.1% | 3.6% | Search Console, 8 weeks |
The click-through change is modest and partly attributable to other work in the period; the reliable gains are complete, valid markup and a trail readers can trust.
Search Console's enhancement report showed four remaining invalid pages, all generated API pages whose titles contained unescaped angle brackets from type signatures; using navTitle for them fixed the last four.
Pitfalls & Rollback
- Building JSON-LD by string concatenation. Use
JSON.stringify. - Separate code for the visible trail and the JSON-LD. They drift apart; generate both from one array.
- Linking folders without pages. Skip them or create index pages.
- Preview hosts in structured data. Use
Astro.site, the production URL. - Rollback: the component replaces the old breadcrumbs in one layout; reverting the layout change restores them.
Conclusion
Breadcrumbs in Astro are best built once, as an array of names and absolute URLs derived from the path and titled from the content collection, then rendered twice — as an accessible nav and as BreadcrumbList JSON-LD. On a 1,300-page docs site that gave every page valid breadcrumb markup, removed 2,140 slug-named crumbs and 87 links to missing pages, and a 6-second CI check keeps the two outputs in agreement.
FAQ
Should breadcrumbs come from the URL or from the content hierarchy?
From the content hierarchy when the site has one that differs from URLs, and from the URL when the URL structure mirrors the hierarchy. Deriving from the URL is simpler but produces slug-like names unless each level has a page with a title. On most documentation sites with folder-based URLs, URL-derived crumbs with titles looked up from the collection work well.
Do breadcrumbs in JSON-LD have to match the visible breadcrumbs?
They should. Structured data is meant to describe what is on the page, and a mismatch between the JSON-LD and the visible trail can lead search engines to ignore the markup. Generating both from the same array guarantees they agree.
Should the last breadcrumb item have a URL?
In the visible trail, the current page is usually plain text with aria-current set to page. In BreadcrumbList JSON-LD, the last item may omit item, in which case the page's own URL is assumed, or include it. Including it explicitly is clearer and is accepted by validators.
What if an intermediate folder has no page?
Then that level has no URL to link to. Either create an index page for the folder, which is usually better for readers, or skip the level in the trail. A breadcrumb that links to a 404 is worse than a shorter trail, and a CI check should catch it.
Related
- Parent: Technical SEO for Static Sites — structured data and the rest of technical SEO.
- Adding JSON-LD Structured Data at Build Time — other schema types.
- Testing Structured Data and Meta Tags — validation in CI.
- Sidebar Navigation in Astro and Eleventy — the other navigation built from the same hierarchy.
- Skip Links and Landmarks in SSG Layouts — naming the breadcrumb navigation landmark.