Semua artikel

JSON-LD in Next.js 16 App Router: SoftwareApplication, FAQPage, and 3 traps I tested

A typed JSON-LD component for the Next.js 16 App Router, tested: the XSS escape, why next/script hides it, and what Google still shows.

Nando Septian Husni (Open-Source)9 min read0 kali dilihat
JSON-LD in Next.js 16 App Router: SoftwareApplication, FAQPage, and 3 traps I tested

The Next.js docs recommend one thing for JSON-LD: render a plain <script type="application/ld+json"> from your layout.js or page.js. The traps are around it: a product name with </script> in it runs code on your page, next/script keeps the data out of your HTML, and Google changed what it shows for SoftwareApplication and FAQPage.

I built every snippet below in a fresh create-next-app project on Next.js 16.5.0, React 19.3.1, TypeScript 5.9.3 and schema-dts 2.1.0, ran next build and next start, and checked the pages with Playwright.

1. A typed <JsonLd> component

// components/json-ld.tsx
import type { Thing, WithContext } from "schema-dts";

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

It has no "use client", so it renders on the server and the component isn't part of your client JavaScript. The types come from schema-dts, which the Next.js docs suggest (npm i schema-dts). They catch typos at build time. I misspelled one property on purpose, and this is what next build printed:

app/typo/page.tsx(8,3): error TS2561: Object literal may only specify known properties, but 'operatingSytem' does not exist in type 'SoftwareApplicationLeaf & { "@context": "https://schema.org"; }'. Did you mean to write 'operatingSystem'?
Failed to type check.

2. Why the < escape matters

The docs warn that JSON.stringify doesn't sanitize strings for HTML, and suggest replacing < with \u003c. To see what happens without it, I used a product name that could come from a CMS field someone else edits:

// app/xss-unsafe/page.tsx
const name = 'Example Notes</script><script>window.__injected = true</script>';

export default function Page() {
  const jsonLd = {
    "@context": "https://schema.org",
    "@type": "SoftwareApplication",
    name,
  };
  return (
    <main>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
      />
      <h1>Unsafe</h1>
    </main>
  );
}

This is the HTML that next start served:

<script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"Example Notes</script><script>window.__injected = true</script>"}</script>

The browser ends the JSON-LD block at the first </script> and runs the next tag as code. In Playwright, window.__injected was true. React then threw a hydration error: "Minified React error #418" in production, and "Hydration failed because the server rendered HTML didn't match the client" in next dev. The JSON-LD in the served HTML was also broken JSON.

The same name through <JsonLd> comes out as:

<script type="application/ld+json">{"@context":"https://schema.org","@type":"SoftwareApplication","name":"Example Notes\u003c/script>\u003cscript>window.__injected = true\u003c/script>"}</script>

Nothing ran, there was no hydration error, and JSON.parse on the script's text returned the original name, character for character. \u003c is a valid JSON escape, so parsers read it as <.

3. Site-wide data in the layout, page data in the page

Things that describe the whole site go in the root layout, so every page gets them:

// app/layout.tsx
import type { WebSite, WithContext } from "schema-dts";
import { JsonLd } from "@/components/json-ld";
import "./globals.css";

const website: WithContext<WebSite> = {
  "@context": "https://schema.org",
  "@type": "WebSite",
  name: "Example Notes",
  url: "https://example.com",
};

export default function RootLayout({ children }: LayoutProps<"/">) {
  return (
    <html lang="en">
      <body>
        <JsonLd data={website} />
        {children}
      </body>
    </html>
  );
}

The script lands in <body>, not <head>. That's fine: Google's structured data intro describes JSON-LD as a <script> tag in the <head> and <body> elements, and the Next.js docs example renders it inside a <section>. A page can have several blocks: my home page has three.

4. SoftwareApplication: what Google needs for a rich result

Google's software app docs list three required things:

  • name
  • offers.price (use 0 for a free app; add priceCurrency when the price is above 0)
  • a rating or a review: aggregateRating or review

applicationCategory (from a fixed list, such as BusinessApplication or DeveloperApplication) and operatingSystem are recommended.

Google's review snippet guidelines say users should be able to see the aggregate rating on the page, that you shouldn't aggregate ratings from other websites, and that fake reviews aren't allowed. So only add aggregateRating when you have real ratings, and show them:

// app/page.tsx (excerpt)
export default async function Home() {
  const rating = await getRating(); // { value, count } or null

  const app: WithContext<SoftwareApplication> = {
    "@context": "https://schema.org",
    "@type": "SoftwareApplication",
    name: "Example Notes",
    applicationCategory: "BusinessApplication",
    operatingSystem: "Web",
    url: "https://example.com",
    offers: {
      "@type": "Offer",
      price: 12,
      priceCurrency: "USD",
    },
    ...(rating && {
      aggregateRating: {
        "@type": "AggregateRating",
        ratingValue: rating.value,
        ratingCount: rating.count,
      },
    }),
  };

  return (
    <main className="mx-auto max-w-2xl p-8">
      <JsonLd data={app} />
      <h1 className="text-3xl font-semibold">Example Notes</h1>
      <p>Notes for small teams. $12 per month.</p>
      {rating && (
        <p>
          Rated {rating.value} out of 5 by {rating.count} users
        </p>
      )}
    </main>
  );
}

getRating() is a stub in my test project that returns null. I built it both ways: with null, there's no aggregateRating key at all, and with sample data the HTML had "aggregateRating":{"@type":"AggregateRating","ratingValue":4.6,"ratingCount":38} plus the visible line.

If you have no ratings yet, you can still ship the markup. It just isn't eligible for Google's software app rich result.

5. FAQPage: no Google rich result since May 2026

Google added a deprecation notice to its FAQ rich result docs in May 2026: the feature stopped appearing in Google Search starting May 7, 2026. In June it removed the FAQ docs. If a checklist tells you to add FAQPage to get a bigger Google result, that advice is out of date.

If your page has an FAQ anyway, the markup costs little. Build the visible FAQ and the JSON-LD from one array, so they can't drift. Google's general guidelines say not to mark up content that readers can't see.

// lib/faq.ts
export const faqs = [
  {
    question: "Is there a free plan?",
    answer: "Yes. The free plan includes 3 projects and never expires.",
  },
  {
    question: "Can I cancel any time?",
    answer: "Yes. Cancel from the billing page and you keep access until the end of the period.",
  },
];
// app/page.tsx (excerpt)
const faqPage: WithContext<FAQPage> = {
  "@context": "https://schema.org",
  "@type": "FAQPage",
  mainEntity: faqs.map((f) => ({
    "@type": "Question",
    name: f.question,
    acceptedAnswer: { "@type": "Answer", text: f.answer },
  })),
};

// inside the returned JSX
<JsonLd data={faqPage} />
{faqs.map((f) => (
  <details key={f.question}>
    <summary>{f.question}</summary>
    <p>{f.answer}</p>
  </details>
))}

6. Don't use next/script for JSON-LD

The Next.js docs say it directly: next/script is for loading and running JavaScript, and JSON-LD isn't code. I tried it anyway:

<Script
  id="app-jsonld"
  type="application/ld+json"
  dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>

The default strategy is afterInteractive, which the docs describe as injected client-side. In the served HTML, the data only existed as an escaped string inside the React Server Components payload. Counting real tags:

curl -s http://localhost:3000/next-script | grep -o '<script type="application/ld+json">' | wc -l
1

That one is the WebSite block from the layout. After hydration, Playwright found two blocks in the DOM. A static export (output: "export") gave the same result: out/index.html had all three JSON-LD tags, while out/next-script.html had only the WebSite one from the layout.

Google says it can read structured data that JavaScript adds once it renders the page. Anything that reads only the raw HTML won't see it, and a plain <script> costs nothing, so use that.

7. Check the built HTML with a zero-dependency script

Before deploying, I run this against next start. It uses the built-in fetch, so it needs Node 18 or later (I ran it on Node 22):

// scripts/check-jsonld.mjs
// Usage: node scripts/check-jsonld.mjs http://localhost:3000/ http://localhost:3000/pricing
const urls = process.argv.slice(2);
let failed = false;

for (const url of urls) {
  const html = await fetch(url).then((r) => r.text());
  const blocks = [
    ...html.matchAll(/<script type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/g),
  ];
  if (blocks.length === 0) {
    console.log(`✗ ${url}: no JSON-LD in the HTML`);
    failed = true;
    continue;
  }
  for (const [, raw] of blocks) {
    let data;
    try {
      data = JSON.parse(raw);
    } catch (e) {
      console.log(`✗ ${url}: invalid JSON (${e.message})`);
      failed = true;
      continue;
    }
    const notes = [];
    if (data["@context"] !== "https://schema.org") notes.push("missing @context");
    if (data["@type"] === "SoftwareApplication") {
      if (!data.name) notes.push("missing name");
      if (data.offers?.price === undefined) notes.push("missing offers.price");
      if (!data.aggregateRating && !data.review)
        notes.push("no aggregateRating or review, so no Google rich result");
    }
    if (data["@type"] === "FAQPage")
      notes.push("Google no longer shows FAQ rich results");
    console.log(`${notes.length ? "!" : "✓"} ${url}: ${data["@type"]}${notes.length ? ": " + notes.join("; ") : ""}`);
  }
}

process.exit(failed ? 1 : 0);

Output on my test app, with no ratings:

✓ http://localhost:3000/: WebSite
! http://localhost:3000/: SoftwareApplication: no aggregateRating or review, so no Google rich result
! http://localhost:3000/: FAQPage: Google no longer shows FAQ rich results
✓ http://localhost:3000/xss-unsafe: WebSite
✗ http://localhost:3000/xss-unsafe: invalid JSON (Unterminated string in JSON at position 84 (line 1 column 85))

It exits with code 1 on missing or broken JSON-LD, so it can fail a CI step. The regex only matches tags written the way React renders them. For the final check, the Next.js docs point to Google's Rich Results Test and the Schema Markup Validator.

Wrap-up

  1. Use a plain <script> in a Server Component, not next/script.
  2. Always replace < with \u003c. One </script> in your data is enough to run code.
  3. Site-wide entities go in the root layout, page entities in the page.
  4. SoftwareApplication needs name, offers.price, and a real rating or review.
  5. FAQPage gets no Google rich result now. Build it from the same array as the visible FAQ.
  6. Check the served HTML, not just the DOM.

Which schema types do you add to your Next.js sites, and have you seen any of them change how your pages show up in search?

I keep launch checks like these as free, MIT-licensed agent skills for Claude Code, Cursor and Codex: npx skills add nandot12/nextjs-launch-skills · GitHub


Sumber artikel open-source oleh Nando Septian Husni di DEV Community — Baca artikel asli. Topik: #nextjs #react #webdev #seo

Sukai & bagikan artikel ini

Ditulis & Dikurasi Oleh

Nando Septian Husni (Open-Source)

Software Engineer yang berfokus pada Next.js, TypeScript, arsitektur backend skalabel, Cloud, dan Applied AI.

Semua artikel

Komentar