🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
SEO••By Komal Nakrani

Astro JSON-LD: Add Structured Data the Right Way

Astro JSON-LD guide: render schema.org structured data with set:html, build Article, Organization, Breadcrumb and Product schema, type it, and escape it safely.

#Astro#JSON-LD#Structured Data#SEO#Schema

To add JSON-LD in Astro, build the schema as a plain JavaScript object in the component frontmatter and render it with <script type="application/ld+json" set:html={JSON.stringify(schema)} />. Astro outputs it as static HTML, so Google and other crawlers read it without running any JavaScript.

That one line is the whole mechanism. The rest is deciding which schema types to use, generating them from your content, and escaping the output so a stray </script> in a title can’t break the page.

Key Takeaways

  • Use set:html={JSON.stringify(schema)} on a type="application/ld+json" script. Writing {JSON.stringify(schema)} as a child escapes the quotes and breaks the JSON.
  • Escape < as < in the output so content can never close the script tag early.
  • Combine related entities in one @graph and link them with @id, instead of scattering separate blocks.
  • Generate schema from frontmatter and Astro.site, so it always matches the visible page.
  • Validate with Google’s Rich Results Test and the Schema Markup Validator after every template change.

What JSON-LD does

JSON-LD is a way to describe a page in schema.org vocabulary: this page is a BlogPosting by this Person, published on this date, part of this WebSite. Search engines use it to understand entities and, for supported types, to show rich results such as breadcrumbs in the URL line, product prices and ratings, or event dates.

Google recommends JSON-LD over Microdata and RDFa because it lives in one block and doesn’t tangle with your markup. In Astro that’s convenient: the schema is data you build in the frontmatter, separate from the template.

Structured data doesn’t directly raise rankings, and it doesn’t guarantee a rich result. It makes your page eligible and removes ambiguity about what the page is. It also gives AI answer engines a clean, machine-readable summary of the page’s facts.

The basic pattern in Astro

---
// src/components/JsonLd.astro
interface Props {
  schema: Record<string, unknown>;
}

const { schema } = Astro.props;
// Escape "<" so a value containing "</script>" can't end the tag early
const json = JSON.stringify(schema).replace(/</g, '\\u003c');
---
<script type="application/ld+json" set:html={json} />

Two details matter here.

First, set:html. Astro escapes expressions rendered as children, which is what you want for normal text. Inside a JSON-LD script, though, escaping turns every " into &quot; and the JSON becomes invalid. set:html inserts the string as-is.

Second, the replace. JSON.stringify doesn’t escape <, so a post title like Fixing </script> errors would close the script element and spill the rest into the page. Replacing < with its Unicode escape keeps the JSON identical in meaning and makes that impossible.

Astro also treats any script with a type attribute as inline, so it won’t try to bundle or process this one.

Article schema for blog posts

For posts in a content collection, build the schema from the entry’s data:

---
// src/layouts/PostLayout.astro
import JsonLd from '../components/JsonLd.astro';

interface Props {
  title: string;
  description: string;
  pubDate: Date;
  updatedDate?: Date;
  image?: string;
  author: string;
}

const { title, description, pubDate, updatedDate, image = '/og/default.jpg', author } = Astro.props;
const url = new URL(Astro.url.pathname, Astro.site).href;

const schema = {
  '@context': 'https://schema.org',
  '@type': 'BlogPosting',
  headline: title,
  description,
  image: new URL(image, Astro.site).href,
  datePublished: pubDate.toISOString(),
  dateModified: (updatedDate ?? pubDate).toISOString(),
  author: { '@type': 'Person', name: author },
  mainEntityOfPage: { '@type': 'WebPage', '@id': url },
};
---
<html lang="en">
  <head>
    <JsonLd schema={schema} />
  </head>
  <body><slot /></body>
</html>

Use BlogPosting for blog posts, NewsArticle for news, TechArticle for technical documentation, or plain Article when none fits. Google treats them all as article structured data.

Keep the values honest. dateModified should change only when the content meaningfully changes, and headline should match the visible <h1>. Schema that disagrees with the page is a quality signal against you, not for you.

Organization and WebSite for the whole site

Every page can describe who publishes it. Put this in the base layout:

// src/data/schema.ts
const SITE = 'https://www.example.com';

export const organization = {
  '@type': 'Organization',
  '@id': `${SITE}/#organization`,
  name: 'Example Studio',
  url: `${SITE}/`,
  logo: `${SITE}/logo.png`,
  sameAs: [
    'https://github.com/example-studio',
    'https://www.linkedin.com/company/example-studio',
  ],
};

export const website = {
  '@type': 'WebSite',
  '@id': `${SITE}/#website`,
  name: 'Example Studio',
  url: `${SITE}/`,
  publisher: { '@id': `${SITE}/#organization` },
};

The @id values are stable identifiers. Other entities point at them with { '@id': ... } instead of repeating the full object, which is how you build one connected description of the site.

Combine entities with @graph

Instead of three separate script tags, put everything for a page in one @graph:

---
// src/layouts/BaseLayout.astro
import JsonLd from '../components/JsonLd.astro';
import { organization, website } from '../data/schema';

const { title, description, breadcrumbs = [] } = Astro.props;
const pageUrl = new URL(Astro.url.pathname, Astro.site).href;

const graph = {
  '@context': 'https://schema.org',
  '@graph': [
    organization,
    website,
    {
      '@type': 'WebPage',
      '@id': `${pageUrl}#webpage`,
      url: pageUrl,
      name: title,
      description,
      isPartOf: { '@id': website['@id'] },
    },
    breadcrumbs.length > 0 && {
      '@type': 'BreadcrumbList',
      itemListElement: breadcrumbs.map((crumb, i) => ({
        '@type': 'ListItem',
        position: i + 1,
        name: crumb.name,
        item: new URL(crumb.path, Astro.site).href,
      })),
    },
  ].filter(Boolean),
};
---
<head>
  <JsonLd schema={graph} />
</head>

A page passes its trail:

<BaseLayout
  title="Pricing"
  description="Plans and prices."
  breadcrumbs={[
    { name: 'Home', path: '/' },
    { name: 'Pricing', path: '/pricing/' },
  ]}
>

The BreadcrumbList is what lets Google show “example.com > Pricing” in the result instead of the raw URL. If you already render visible breadcrumbs, generate both from the same array. The Astro breadcrumbs component builds the visible trail and its schema together.

Product, FAQ and other types

Use types that describe what the page really is:

Page Schema type Rich result potential
Blog post BlogPosting Article enhancements
Product or theme page Product with Offer Price, availability, reviews
Software or app page SoftwareApplication Rating, price
Event page Event Date, location
Local business LocalBusiness Knowledge panel details
Q&A section FAQPage Limited (see below)
How-to guide HowTo No longer shown by Google

A product example:

// src/pages/products/[slug].astro (frontmatter excerpt)
const schema = {
  '@context': 'https://schema.org',
  '@type': 'Product',
  name: product.name,
  description: product.description,
  image: new URL(product.image, Astro.site).href,
  offers: {
    '@type': 'Offer',
    price: product.price.toFixed(2),
    priceCurrency: 'USD',
    availability: 'https://schema.org/InStock',
    url: new URL(Astro.url.pathname, Astro.site).href,
  },
};

Only add aggregateRating or review when you display real reviews on the page. Invented ratings are a manual-action risk.

For FAQs: since August 2023 Google shows FAQ rich results only for a small set of authoritative government and health sites. FAQPage markup is still valid schema, and other search engines and AI systems can read it, so it’s reasonable to keep on pages with a real FAQ section. Just don’t expect the expanded result in Google. The FAQ section with schema component generates the markup from the same data as the visible questions.

Type your schema with schema-dts

Plain objects are easy to get wrong: a misspelled datePublised fails silently. Google’s schema-dts package provides TypeScript types for the whole vocabulary:

npm install -D schema-dts
// src/data/schema.ts
import type { Organization, WithContext, BlogPosting } from 'schema-dts';

export function blogPosting(data: {
  title: string;
  url: string;
  published: Date;
}): WithContext<BlogPosting> {
  return {
    '@context': 'https://schema.org',
    '@type': 'BlogPosting',
    headline: data.title,
    url: data.url,
    datePublished: data.published.toISOString(),
  };
}

It’s a types-only dependency, so nothing ships to the browser. Your editor now autocompletes property names and flags typos.

Validate the output

After npm run build, check the rendered HTML, not your source:

  1. Run npm run preview and paste a page URL (via a tunnel) or its HTML into Google’s Rich Results Test. It reports which rich results the page is eligible for and any errors.
  2. Use the Schema Markup Validator for a vocabulary-level check of types that Google doesn’t show as rich results.
  3. After deploy, watch the Enhancements reports in Search Console for errors across all pages.

A quick local check that every post has exactly one JSON-LD block:

npm run build
grep -c 'application/ld+json' dist/blog/*/index.html | grep -v ':1$'

Any file listed has zero or more than one block.

Common mistakes

  • Rendering JSON as a child. <script type="application/ld+json">{JSON.stringify(schema)}</script> produces escaped quotes. Use set:html.
  • Relative URLs. image: '/og/post.jpg' is ambiguous to some parsers. Build absolute URLs with new URL(path, Astro.site).
  • Schema for content that isn’t visible. Markup must describe what users can see.
  • Duplicate blocks. A layout and a page both emitting Organization creates conflicting entities. Keep site-wide entities in one place.
  • Forgetting site. Without site in the config, Astro.site is undefined and every URL is wrong.

Structured data sits alongside your other head tags; the reusable meta tags component handles titles, canonicals and Open Graph, and the Astro SEO checklist ties it all together. If you’re building a product or portfolio site and want a finished starting point, you can browse Astro themes and add schema to the layouts they already have. The Astro config docs cover setting site.

FAQ

How do I add JSON-LD to an Astro page?

Build the schema object in the component frontmatter and render <script type="application/ld+json" set:html={JSON.stringify(schema)} /> inside the head. Astro outputs it as static HTML at build time.

Why does my Astro JSON-LD show escaped quotes?

The JSON was rendered as a child expression, which Astro escapes. Pass it through set:html instead, so the string is inserted without HTML escaping.

Should JSON-LD go in the head or body?

Either works for Google. The head is the usual choice because it keeps metadata together and a layout can manage it in one place.

Can I have multiple JSON-LD blocks on one page?

Yes, but a single block with an @graph array is easier to maintain and lets entities reference each other by @id. Avoid two blocks that describe the same entity differently.

Does JSON-LD help with AI search and citations?

It gives AI crawlers a structured summary of the page’s facts, such as author, dates, product prices and organization details. It isn’t a guarantee of citation, but it removes ambiguity about who published what and when.