React.js

Implement JSON-LD in Next.js

Search engines can read a page’s text, but they have to guess what it means. Structured data removes the guesswork by describing the page in a machine-readable format: this is an article, written by this person, published on this date, and it sits under this section of the site. This article shows how to add that data to a Next.js (App Router) site as JSON-LD, using a safe reusable component, and how to validate it, both by hand and automatically after every build.

1. Introduction to JSON-LD and Why Validate It After Every Build

1.1 What is JSON-LD?

JSON-LD (JSON for Linking Data) is a way of embedding structured data in a page as a JSON object inside a script tag. The vocabulary usually comes from schema.org, which defines types such as Organization, Article, and BreadcrumbList. A minimal block looks like this:

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Organization",
  "name": "Example Inc.",
  "url": "https://www.example.com"
}
</script>

@context says which vocabulary the keys belong to, and @type says what kind of thing is being described. The remaining keys are the properties of that type. The block is invisible to visitors, and it does not touch the page’s layout. Google recommends JSON-LD over other formats because it lives in one place, separate from the HTML markup. Search engines can use it to show rich results such as breadcrumbs and article details, and to understand which organization owns the site. See Google’s structured data introduction for the supported types.

1.2 Why validate it automatically after every build?

Structured data fails silently. If the JSON is malformed, a required property is missing, or a refactor stops a field from being passed, the page still renders perfectly and no test or error log complains. You only find out weeks later, when rich results disappear from search. Validating by hand with online tools is fine for a one-off check, but it does not scale to every page and every deploy. A short script that reads the built pages and fails the build on bad JSON-LD turns a silent regression into a failed build you can fix before release.

2. Code Example: Adding and Validating JSON-LD in Next.js

The example uses Next.js 15 with the App Router and TypeScript, and the site is the made-up www.example.com. We will build a reusable component, add site-wide data to the home page, add per-article data to a dynamic route, and then validate the output.

2.1 Shared site constants and sample posts

Two small files hold the data the pages need. A real site would load posts from a CMS or database.

// lib/site.ts
export const SITE_URL = "https://www.example.com";
export const SITE_NAME = "Example Inc.";

// lib/posts.ts
export type Post = {
  slug: string;
  title: string;
  author: string;
  image: string;
  publishedAt: string;
  updatedAt: string;
};

export const posts: Post[] = [
  {
    slug: "hello-world",
    title: "Hello World",
    author: "Jane Doe",
    image: "https://www.example.com/images/hello-world.png",
    publishedAt: "2026-01-15",
    updatedAt: "2026-02-01",
  },
  {
    slug: "json-ld-basics",
    title: "JSON-LD Basics",
    author: "John Smith",
    image: "https://www.example.com/images/json-ld-basics.png",
    publishedAt: "2026-03-10",
    updatedAt: "2026-03-10",
  },
];

export const getPost = (slug: string) => posts.find((post) => post.slug === slug);

SITE_URL is kept in one place because structured data needs absolute URLs, unlike links inside the app. Each post carries the fields that the Article type will need later: author, image, and ISO-formatted dates. getPost is the lookup the dynamic route will use.

2.2 Build a safe JsonLd component

Every page needs the same script tag, so we wrap it in a component that also handles the one real security risk.

// components/JsonLd.tsx
type JsonLdProps = {
  data: Record<string, unknown>;
};

export function JsonLd({ data }: JsonLdProps) {
  const json = JSON.stringify({ "@context": "https://schema.org", ...data })
    .replace(/</g, "\\u003c");

  return (
    <script
      type="application/ld+json"
      dangerouslySetInnerHTML={{ __html: json }}
    />
  );
}

The component adds @context for the caller, so each page only describes its own data. The data goes into the tag with dangerouslySetInnerHTML, because React would otherwise HTML-escape the quotes and break the JSON. That makes escaping our job. If a field such as an article title contains </script>, it would close the tag early and let the rest run as page content, which is a cross-site scripting hole. Replacing every < with its Unicode escape \u003c prevents that, and JSON.parse still reads the escaped value back as the original character. This is the same approach the Next.js documentation recommends.

2.3 Add Organization and WebSite data to the home page

Site-wide data belongs on the home page, where search engines look for it first.

// app/page.tsx
import { JsonLd } from "@/components/JsonLd";
import { SITE_NAME, SITE_URL } from "@/lib/site";

export default function HomePage() {
  return (
    <main>
      <JsonLd
        data={{
          "@type": "Organization",
          name: SITE_NAME,
          url: SITE_URL,
          logo: `${SITE_URL}/logo.png`,
          sameAs: [
            "https://github.com/example",
            "https://www.linkedin.com/company/example",
          ],
        }}
      />
      <JsonLd
        data={{
          "@type": "WebSite",
          name: SITE_NAME,
          url: SITE_URL,
        }}
      />
      <h1>Welcome to {SITE_NAME}</h1>
    </main>
  );
}

The page renders two blocks. Organization tells search engines who owns the site, with a logo and links to official profiles under sameAs. WebSite names the site and its canonical address. Both are plain server-rendered markup, so no client JavaScript is needed for crawlers to see them. The home page source now contains these two tags:

<script type="application/ld+json">{"@context":"https://schema.org","@type":"Organization","name":"Example Inc.","url":"https://www.example.com","logo":"https://www.example.com/logo.png","sameAs":["https://github.com/example","https://www.linkedin.com/company/example"]}</script>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"WebSite","name":"Example Inc.","url":"https://www.example.com"}</script>

Each block is a single line of compact JSON, starting with @context because the component spreads the caller’s data after it. This is exactly what a crawler reads. You can check it yourself with View Source on the running page.

2.4 Add Article and Breadcrumb data to a dynamic route

Blog posts live under /blog/[slug]. Each post gets its own Article and BreadcrumbList, built from the post data.

// app/blog/[slug]/page.tsx
import { notFound } from "next/navigation";
import { JsonLd } from "@/components/JsonLd";
import { SITE_URL } from "@/lib/site";
import { getPost, posts } from "@/lib/posts";

export function generateStaticParams() {
  return posts.map((post) => ({ slug: post.slug }));
}

export default async function PostPage({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const post = getPost(slug);
  if (!post) notFound();

  const url = `${SITE_URL}/blog/${post.slug}`;

  return (
    <article>
      <JsonLd
        data={{
          "@type": "Article",
          headline: post.title,
          image: post.image,
          datePublished: post.publishedAt,
          dateModified: post.updatedAt,
          author: { "@type": "Person", name: post.author },
          mainEntityOfPage: url,
        }}
      />
      <JsonLd
        data={{
          "@type": "BreadcrumbList",
          itemListElement: [
            { "@type": "ListItem", position: 1, name: "Home", item: SITE_URL },
            { "@type": "ListItem", position: 2, name: "Blog", item: `${SITE_URL}/blog` },
            { "@type": "ListItem", position: 3, name: post.title, item: url },
          ],
        }}
      />
      <h1>{post.title}</h1>
    </article>
  );
}

In Next.js 15, params is a promise, so the page awaits it before looking up the post, and an unknown slug returns a 404. generateStaticParams makes Next.js prerender one HTML file per post at build time, which is what lets the validation script in section 2.6 read the finished pages from disk. The Article block uses a nested Person for the author, which is how schema.org expresses an object-valued property. The BreadcrumbList lists the path from the home page to the current page, with a 1-based position for each step. For the hello-world post, the page source contains:

<script type="application/ld+json">{"@context":"https://schema.org","@type":"Article","headline":"Hello World","image":"https://www.example.com/images/hello-world.png","datePublished":"2026-01-15","dateModified":"2026-02-01","author":{"@type":"Person","name":"Jane Doe"},"mainEntityOfPage":"https://www.example.com/blog/hello-world"}</script>
<script type="application/ld+json">{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https://www.example.com"},{"@type":"ListItem","position":2,"name":"Blog","item":"https://www.example.com/blog"},{"@type":"ListItem","position":3,"name":"Hello World","item":"https://www.example.com/blog/hello-world"}]}</script>

The values come straight from the post record: the headline, the author name, the two dates, and a three-step breadcrumb ending at this post’s URL. A second post produces the same structure with its own values.

2.5 Validate your structured data manually

Before automating anything, check the output with the two standard tools. Run npm run build && npm start, then:

  • Paste the page’s HTML (or a public URL) into the Rich Results Test. It reports which Google rich result types the page is eligible for, and lists errors and warnings per block.
  • Paste the same into the Schema Markup Validator. It checks the markup against schema.org itself, for any type, not just the ones Google shows as rich results.

For the blog post above, both tools should show one Article and one BreadcrumbList with no errors. They also flag warnings for recommended properties, which do not block the result but are worth reading. These tools need you to paste code or expose a public URL, so they are a poor fit for local development and for CI, which is why the next step adds an automatic check.

2.6 Validate JSON-LD automatically after every build

This script reads the HTML files Next.js produced, pulls out every JSON-LD block, and fails with a non-zero exit code if anything is wrong.

// scripts/validate-jsonld.mjs
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

const root = ".next/server/app";
const required = {
  Organization: ["name", "url"],
  WebSite: ["name", "url"],
  Article: ["headline", "datePublished", "author", "image"],
  BreadcrumbList: ["itemListElement"],
};
const pattern = /<script type="application\/ld\+json">([\s\S]*?)<\/script>/g;

const files = readdirSync(root, { recursive: true }).filter((f) => f.endsWith(".html"));
const errors = [];
let checked = 0;

for (const file of files) {
  const html = readFileSync(join(root, file), "utf8");
  const types = [];

  for (const [, body] of html.matchAll(pattern)) {
    let data;
    try {
      data = JSON.parse(body);
    } catch {
      errors.push(`${file}: JSON-LD block is not valid JSON`);
      continue;
    }
    if (data["@context"] !== "https://schema.org") {
      errors.push(`${file}: @context must be "https://schema.org"`);
    }
    const type = data["@type"];
    if (!type) {
      errors.push(`${file}: block has no @type`);
      continue;
    }
    for (const key of required[type] ?? []) {
      if (data[key] == null || data[key] === "") {
        errors.push(`${file}: ${type} is missing "${key}"`);
      }
    }
    types.push(type);
  }

  if (types.length > 0) {
    checked++;
    console.log(`checked ${file}: ${types.join(", ")}`);
  }
}

if (checked === 0) errors.push("no JSON-LD found in the build output");

if (errors.length > 0) {
  errors.forEach((e) => console.error(`error ${e}`));
  console.error(`Structured data validation failed (${errors.length} ${errors.length === 1 ? "error" : "errors"})`);
  process.exit(1);
}
console.log(`Structured data OK (${checked} pages)`);

Next.js writes the prerendered pages to .next/server/app, for example index.html for the home page and blog/hello-world.html for a post. The script lists every .html file there, extracts each JSON-LD block with a regular expression, and runs three checks: the block must parse as JSON, it must have the schema.org @context and an @type, and it must contain the properties listed in the required table. That table is our own policy and is deliberately a little stricter than Google’s, so extend it as your needs grow. Pages without JSON-LD, such as the 404 page, are skipped, but the script fails if it finds no JSON-LD anywhere, which catches a component that was removed by mistake. Problems are collected and printed together, and process.exit(1) fails whatever runs the script.

Now chain it to the build in package.json.

{
  "scripts": {
    "dev": "next dev",
    "build": "next build && node scripts/validate-jsonld.mjs",
    "start": "next start"
  }
}

Because the validation is chained with &&, it runs only if next build succeeds, and a validation failure makes npm run build fail. That means your CI pipeline and your host’s build step both stop before a broken page is deployed. Chaining explicitly is more reliable than a postbuild script, which some package managers (pnpm, for one) do not run by default. A passing build prints:

checked index.html: Organization, WebSite
checked blog/hello-world.html: Article, BreadcrumbList
checked blog/json-ld-basics.html: Article, BreadcrumbList
Structured data OK (3 pages)

Each line is a prerendered page with the types found on it. The home page has the two site-wide blocks and both posts have an article and a breadcrumb. To see the failure path, remove the author line from the Article data and build again:

error blog/hello-world.html: Article is missing "author"
error blog/json-ld-basics.html: Article is missing "author"
Structured data validation failed (2 errors)

The script names the file and the missing property for each problem, then exits with code 1, so npm run build fails and nothing is deployed. Restore the field and the build passes again.

3. Conclusion

JSON-LD gives search engines an unambiguous description of your pages, and in Next.js it takes little code: one JsonLd component that escapes < safely, site-wide Organization and WebSite data on the home page, and per-page Article and BreadcrumbList data on dynamic routes. Use the Rich Results Test and the Schema Markup Validator to check your markup against Google and schema.org, and add the build-time script so a missing field or broken JSON fails the build instead of quietly costing you rich results. Start with the types your pages genuinely match, keep the data generated from the same source as the visible content so the two never disagree, and grow the required table as you add more types.

Yatin B.

An experienced full-stack engineer and solution architect with expertise in Core Java, Spring/Spring Boot, MVC, Security, AOP, Angular, React, cloud technologies (AWS and GCP), CI/CD (Jenkins), Docker, and Kubernetes. Skilled in designing scalable architectures and building agentic AI solutions, including AI agents, LLM integrations, agent orchestration, and enterprise AI systems.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button