Skip to content

Astro schema

When working with Markdown files in Astro, you can still add unique JSON-LD schema markup to individual pages by using the frontmatter and the setPageBundles function from @astrojs/renderer-server. Here’s how you can do it:

  1. Install the @astrojs/renderer-server package if you haven’t already:
Terminal window
npm install @astrojs/renderer-server
  1. In your Markdown file (e.g., src/pages/my-page.md), add the JSON-LD schema markup as a frontmatter property:
---
# frontmatter
layout: ../layouts/MarkdownLayout.astro
title: My Page
jsonLdSchema: {
"@context": "https://schema.org",
"@type": "Article",
"headline": "My Article Title",
"author": {
"@type": "Person",
"name": "John Doe"
},
"datePublished": "2023-05-01"
}
---
# Markdown content goes here
  1. In your layout file (e.g., src/layouts/MarkdownLayout.astro), import the setPageBundles function from @astrojs/renderer-server and use it to inject the JSON-LD schema markup into the page’s <head> section:
---
import { setPageBundles } from '@astrojs/renderer-server';
const { jsonLdSchema } = Astro.props.frontmatter;
if (jsonLdSchema) {
setPageBundles([
{
type: 'script',
data: `
const script = document.createElement('script');
script.type = 'application/ld+json';
script.textContent = ${JSON.stringify(jsonLdSchema)};
document.head.appendChild(script);
`,
},
]);
}
---
<html>
<head>
<!-- Other head elements -->
</head>
<body>
<slot />
</body>
</html>

In this example, we first check if the jsonLdSchema property exists in the frontmatter of the Markdown file. If it does, we use the setPageBundles function to inject a script that creates a <script> element with the application/ld+json type and appends it to the document’s <head> section with the JSON-LD schema markup as its content.

With this approach, you can define unique JSON-LD schema markup for each Markdown file by adding it as a frontmatter property. The layout file will then handle injecting the schema markup into the page’s <head> section during server-side rendering.

Note that this approach assumes that you’re using a layout file to wrap your Markdown content. If you’re not using a layout file, you can directly import the setPageBundles function and use it in the Markdown file itself, similar to the first example.