Skip to content

Astro Integration

The @unschema-graph/astro package provides first-class support for Astro 5, 6, and 7, including an interactive Dev Toolbar application and Content Collections helpers.


Automatic (CLI)

Terminal window
npx astro add @unschema-graph/astro

pnpm

Terminal window
pnpm add @unschema-graph/astro zod

npm

Terminal window
npm install @unschema-graph/astro zod

yarn

Terminal window
yarn add @unschema-graph/astro zod

bun

Terminal window
bun add @unschema-graph/astro zod

Register the integration in astro.config.mjs:

astro.config.mjs
import { defineConfig } from 'astro/config';
import schemaGraph from '@unschema-graph/astro';
export default defineConfig({
site: 'https://example.com',
integrations: [
schemaGraph({
// Throw during build/CI to prevent bad SEO, warn in dev:
onError: process.env.NODE_ENV === 'production' ? 'throw' : 'warn',
}),
],
});

The named schemaGraph export remains available for existing configurations.

Option Type Default Description
baseUrl string config.site Canonical base URL used to resolve relative #id fragments and URLs.
inLanguage string route locale Default BCP-47 locale when a page has no Astro route locale.
onError 'throw' | 'warn' | 'silent' build: 'throw', dev: 'warn' Validation severity mode.

Resolution is deterministic: a <Schema baseUrl> prop wins over the integration baseUrl, which wins over Astro’s site. Locale precedence is <Schema inLanguage>, then Astro.currentLocale, then the integration default.


Place <Schema /> in your common layout <head> or on specific pages. It serializes entities into <script type="application/ld+json"> with zero client-side JavaScript.

src/layouts/BaseLayout.astro
---
import { Organization, Schema, WebSite } from '@unschema-graph/astro';
interface Props {
title: string;
items?: any[];
}
const { title, items = [] } = Astro.props;
// Global site identity present on all pages
const site = WebSite({
'@id': '#website',
name: 'Acme Corp',
url: 'https://example.com',
publisher: '#organization',
});
const org = Organization({
'@id': '#organization',
name: 'Acme Corp',
url: 'https://example.com',
logo: 'https://example.com/logo.png',
});
---
<!doctype html>
<html lang={Astro.currentLocale ?? 'en'}>
<head>
<meta charset="utf-8" />
<title>{title}</title>
<!-- Renders global entities + page-specific entities in one @graph -->
<Schema items={[site, org, ...items]} />
</head>
<body>
<slot />
</body>
</html>

unschema-graph discovers entities inside the object graph it receives. It traverses nested entity relationships, hoists referenced entities with an @id, deduplicates them, and emits a single, unified @graph.

const organization = Organization({
'@id': '#organization',
name: 'Acme',
});
const article = Article({
'@id': '#article',
headline: 'Hello',
publisher: organization,
});

Passing only article to <Schema /> is enough for organization to be discovered automatically:

Article
↓ publisher
Organization
↓
automatic discovery
↓
Organization promoted into @graph
↓
Article.publisher replaced by { "@id": ... }

However, Astro does not implicitly expose arbitrary variables created in a page component to a parent layout. This is an Astro component and data-flow constraint, not a graph-resolution limitation: page variables must be passed explicitly to the layout through component props.

The recommended pattern is to pass page-level root entities to the layout through a prop such as schemaItems.

src/pages/blog/building-structured-data.astro
---
import BaseLayout from '../../layouts/BaseLayout.astro';
import {
Article,
Organization,
} from '@unschema-graph/astro';
const organization = Organization({
'@id': '#organization',
name: 'Acme Media',
url: 'https://example.com',
});
const article = Article({
'@id': '#article',
headline: 'Building structured data with Astro',
author: 'Ada Lovelace',
publisher: organization,
});
---
<BaseLayout
title="Building structured data with Astro"
schemaItems={[article]}
>
<article>
<h1>Building structured data with Astro</h1>
</article>
</BaseLayout>

Only article is passed to schemaItems. organization does not need to be passed separately because it is reachable through article.publisher and is discovered automatically by the graph engine.

In the shared layout, define schemaItems in Props using the public SchemaOrgEntity type, and pass it to <Schema items={schemaItems} />:

src/layouts/BaseLayout.astro
---
import { Schema } from '@unschema-graph/astro';
import type { SchemaOrgEntity } from '@unschema-graph/astro';
interface Props {
title: string;
schemaItems?: SchemaOrgEntity[];
}
const {
title,
schemaItems = [],
} = Astro.props;
---
<html lang="en">
<head>
<title>{title}</title>
<Schema items={schemaItems} />
</head>
<body>
<slot />
</body>
</html>

You only need to pass the root entities you want to render. Related entities that are embedded in those objects and have an @id are discovered and promoted into the graph automatically.

This pattern is recommended because it:

  • Keeps schema creation close to the page and content that owns it.
  • Keeps the shared layout responsible for rendering one <Schema /> in <head>.
  • Preserves a single unified JSON-LD script and @graph.
  • Avoids duplicate <Schema /> instances across nested page and layout composition.
  • Requires no middleware or global state.
  • Works naturally with Astro’s explicit props model.

The boundary between Astro and unschema-graph follows two distinct steps:

Astro data flow:
Page
↓ explicit prop
BaseLayout
↓
<Schema items={schemaItems} />
unschema-graph data flow:
root entities
↓
relationship traversal
↓
entity discovery
↓
ID resolution
↓
deduplication
↓
single @graph
  • <Schema /> directly in each page: Valid, but if the layout also renders structured data, pages can end up with multiple JSON-LD scripts or graphs. While multiple scripts are valid HTML, the layout-prop pattern is preferable when the project wants one centralized @graph.
  • Build every schema in the layout: Possible, but less modular because the layout must anticipate and inspect page-specific content.
  • Global middleware, context, or store: Possible in custom architectures, but unnecessary for standard static or SSR Astro applications.

In development mode (astro dev), @unschema-graph/astro automatically adds an interactive icon to the Astro Dev Toolbar at the bottom of your browser window.

  • Entity Inspector: Lists every entity detected in the page’s @graph with its primary @type and resolved @id.
  • Graph diagnostics: Shows broken local references and duplicate merge conflicts reported during server rendering.
  • Render context: Displays node count, effective baseUrl, locale, and warning count.
  • JSON-LD copy: Copies the generated payload for external inspection or testing.

The component remains server-rendered and ships no client JavaScript. Toolbar metadata is attached as inert data-* attributes and is only consumed by Astro’s development toolbar.


5. Content Collections & Content Layer Helpers

Section titled “5. Content Collections & Content Layer Helpers”

When rendering Markdown or MDX entries from Astro Content Collections, @unschema-graph/astro/content provides pre-built transformers:

src/pages/blog/[slug].astro
---
import { getEntry, render } from 'astro:content';
import { toBlogPosting } from '@unschema-graph/astro/content';
import BaseLayout from '../../layouts/BaseLayout.astro';
const post = await getEntry('blog', Astro.params.slug!);
if (!post) return Astro.redirect('/404');
const { Content } = await render(post);
// Automatically maps title, description, pubDate, and author to BlogPosting
const blogPosting = toBlogPosting(post, {
url: Astro.url.href,
publisher: '#organization',
});
---
<BaseLayout title={post.data.title} items={[blogPosting]}>
<article>
<h1>{post.data.title}</h1>
<Content />
</article>
</BaseLayout>

Available helpers:

  • toArticle(entry, overrides?)
  • toBlogPosting(entry, overrides?)
  • toNewsArticle(entry, overrides?)

Learn more about Content Collections mapping →