Dev.to WebDev 🛠 Dev 👁 0 📖 4 min read

JSON-LD in the Next.js App Router: typed, safe, in the initial HTML, and in sync with the page

Structured data is one of the few SEO tasks that lands squarely on the developer's desk. Marketing asks for "schema", someone pastes a JSON-LD snippet from a generator into the layout, and a year later the price in the m

Structured data is one of the few SEO tasks that lands squarely on the developer's desk. Marketing asks for "schema", someone pastes a JSON-LD snippet from a generator into the layout, and a year later the price in the markup no longer matches the price on the page.

Here is a setup for the App Router that avoids the usual problems: the markup is typed, rendered on the server, escaped correctly, built from the same data as the visible page, and tested.

Why it matters, briefly

Structured data doesn't improve rankings by itself. It makes pages eligible for rich results such as product price and availability, breadcrumbs or article details, and it helps search engines understand the entities on a page. Google requires the markup to describe content that is visible on the page; markup that contradicts the page can cost eligibility.

That last rule is the technical requirement hiding in an SEO guideline: the JSON-LD and the rendered page must come from the same source of truth.

Render it in a Server Component

In the App Router, the simplest correct approach is a plain <script type="application/ld+json"> rendered by a Server Component. It ends up in the initial HTML, so crawlers that don't execute JavaScript still see it. Avoid injecting JSON-LD from a client-side effect, and don't load it through next/script with a deferred strategy; neither guarantees that the markup is in the HTML response.

// app/products/[slug]/page.tsx
import type { Product, WithContext } from "schema-dts";
import { getProduct } from "@/lib/products";
import { JsonLd } from "@/components/json-ld";

const SITE = "https://example.com";

export default async function ProductPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const product = await getProduct(slug);
  const url = `${SITE}/products/${slug}`;
  const price = product.price.toFixed(2);

  const jsonLd: WithContext<Product> = {
    "@context": "https://schema.org",
    "@type": "Product",
    "@id": `${url}#product`,
    name: product.name,
    description: product.description,
    image: product.images.map((image) => image.url),
    sku: product.sku,
    brand: { "@type": "Brand", name: product.brand },
    offers: {
      "@type": "Offer",
      url,
      price,
      priceCurrency: "EUR",
      availability: product.inStock
        ? "https://schema.org/InStock"
        : "https://schema.org/OutOfStock",
    },
  };

  return (
    <>
      <JsonLd data={jsonLd} />
      <h1>{product.name}</h1>
      <p>{price} EUR</p>
      <p>{product.inStock ? "In stock" : "Out of stock"}</p>
    </>
  );
}

The price variable feeds both the markup and the visible text. That is the whole trick for keeping them in sync: never compute a value twice.

Escape it properly

The JSON-LD component is tiny, and one line in it matters for security:

// components/json-ld.tsx
export function JsonLd({ data }: { data: object }) {
  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{
        __html: JSON.stringify(data).replace(/</g, "\\u003c"),
      }}
    />
  );
}

JSON.stringify alone is not safe inside a script tag. If a product description from your CMS contains </script>, it ends the tag early and whatever follows is parsed as HTML. Replacing < with its Unicode escape keeps the JSON valid and the document intact. The Next.js documentation recommends the same.

Type it

The schema-dts package provides TypeScript types for the Schema.org vocabulary. It catches misspelled properties and wrong value types at build time. It does not know Google's rich result requirements, which are stricter per feature; a perfectly typed Product can still lack what Google needs for a product snippet. Types prevent typos, validators check eligibility.

Connect entities with @id

Site-wide entities like your organization and website belong in the root layout, and page-level entities can reference them instead of repeating them:

// app/layout.tsx (inside <body>)
<JsonLd
  data={{
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "Organization",
        "@id": "https://example.com/#organization",
        name: "Example Ltd",
        url: "https://example.com/",
        logo: "https://example.com/logo.png",
      },
      {
        "@type": "WebSite",
        "@id": "https://example.com/#website",
        url: "https://example.com/",
        publisher: { "@id": "https://example.com/#organization" },
      },
    ],
  }}
/>

An article page can then set publisher: { "@id": "https://example.com/#organization" }. Stable @id values turn several disconnected blocks into one graph, which is easier to maintain and easier for consumers to interpret.

Test it in CI

Validators are manual tools. A small check against a preview deployment catches the regressions that matter: markup that disappeared, no longer parses, or lost a required field.

// scripts/check-jsonld.ts
const urls = process.argv.slice(2);

for (const url of urls) {
  const html = await (await fetch(url)).text();
  const blocks = [...html.matchAll(
    /<script type="application\/ld\+json">([\s\S]*?)<\/script>/g,
  )].map((match) => JSON.parse(match[1]));

  const product = blocks.find((block) => block["@type"] === "Product");
  if (!product?.offers?.price || !product?.name) {
    console.error(`Missing Product markup or required fields on ${url}`);
    process.exitCode = 1;
  }
}

Run it against one URL per template. JSON.parse failing is a test failure too, which is exactly what you want.

Before and after release

Run Google's Rich Results Test on a sample of each template after changes to the markup, and the Schema Markup Validator if you also care about general Schema.org validity. Then watch Search Console's enhancement reports for new errors.

Samples miss the errors that only occur on some products or categories, so a full crawl helps periodically. Crawl Foundry Site Audit validates detected markup on every crawled URL against Schema.org and Google's rich result requirements and groups recurring findings, which usually point to one template. See the Site Audit feature page.

For which types are worth implementing and how they relate to rich results, the Crawl Foundry glossary entry on schema markup is a good companion to this post.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.