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.
1. Installation
Section titled “1. Installation”Automatic (CLI)
npx astro add @unschema-graph/astropnpm
pnpm add @unschema-graph/astro zodnpm
npm install @unschema-graph/astro zodyarn
yarn add @unschema-graph/astro zodbun
bun add @unschema-graph/astro zod2. Configuration
Section titled “2. Configuration”Register the integration in 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.
Options Reference
Section titled “Options Reference”| 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.
3. The <Schema /> Astro Component
Section titled “3. The <Schema /> Astro Component”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.
---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 pagesconst 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>Passing page entities to a layout
Section titled “Passing page entities to a layout”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 ↓ publisherOrganization ↓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 schemaItems layout pattern
Section titled “The schemaItems layout pattern”The recommended pattern is to pass page-level root entities to the layout through a prop such as schemaItems.
---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} />:
---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
@idare discovered and promoted into the graph automatically.
Why this approach is recommended
Section titled “Why this approach is recommended”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.
Mental model
Section titled “Mental model”The boundary between Astro and unschema-graph follows two distinct steps:
Astro data flow:
Page ↓ explicit propBaseLayout ↓<Schema items={schemaItems} />
unschema-graph data flow:
root entities ↓relationship traversal ↓entity discovery ↓ID resolution ↓deduplication ↓single @graphAlternative approaches
Section titled “Alternative approaches”<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.
4. Astro Dev Toolbar App
Section titled “4. Astro Dev Toolbar App”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.
What the Dev Toolbar offers:
Section titled “What the Dev Toolbar offers:”- Entity Inspector: Lists every entity detected in the page’s
@graphwith its primary@typeand 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:
---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 BlogPostingconst 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?)