Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ export default defineConfig({
lang: "en",
},
},
routeMiddleware: "./src/plugins/toc-formatting-middleware.ts",
routeMiddleware: [
"./src/plugins/toc-formatting-middleware.ts",
"./src/plugins/techarticle-json-ld-middleware.ts",
],
components: {
Head: "./src/components/Head.astro",
},
Expand Down
53 changes: 53 additions & 0 deletions src/plugins/techarticle-json-ld-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { defineRouteMiddleware } from "@astrojs/starlight/route-data";

const ORGANIZATION = {
"@type": "Organization",
name: "System76",
url: "https://system76.com",
};

// Adds schema.org TechArticle structured data (JSON-LD) to every docs page.
export const onRequest = defineRouteMiddleware((context) => {
const { starlightRoute } = context.locals;

// The 404 page and the landing pages (home has an empty id, plus archive) aren't articles.
if (["404", "", "archive"].includes(starlightRoute.id)) {
return;
}

// Starlight already puts the canonical URL in the head. Reuse it so the URL carries the right
// host and the /tech-docs base on every environment. Without a canonical (no `site` set), skip.
const canonical = starlightRoute.head.find(
(tag) => tag.tag === "link" && tag.attrs?.rel === "canonical",
)?.attrs?.href;

if (typeof canonical !== "string") {
return;
}

const { title, description } = starlightRoute.entry.data;
const { lastUpdated } = starlightRoute;

const jsonLd = {
"@context": "https://schema.org",
"@type": "TechArticle",
headline: title,
description,
url: canonical,
mainEntityOfPage: { "@type": "WebPage", "@id": canonical },
// Taken from git history when available. There is no publish date to use.
dateModified: lastUpdated?.toISOString(),
inLanguage: starlightRoute.lang,
author: ORGANIZATION,
publisher: ORGANIZATION,
};

starlightRoute.head.push({
tag: "script",
attrs: { type: "application/ld+json" },
// Drop empty fields, and escape "<" so page text can't close the script tag.
content: JSON.stringify(
Object.fromEntries(Object.entries(jsonLd).filter(([, value]) => value)),
).replace(/</g, "\\u003c"),
});
});
Loading