Implementing JSON-LD in Next.js – Structured Data for SEO and Smart Engines

JSON-LD is a structured data format that helps search engines and AI understand the content and context of your pages. This article explains how to embed JSON-LD in Next.js pages, prevent XSS vulnerabilities, validate schema markup, and type your data with TypeScript.

JSON-LDSEOSchema.orgXSS Sanitization

~2 min read • Updated Oct 28, 2025

Introduction


JSON-LD is a structured data format used by search engines like Google to better understand the meaning and relationships within your page content. It can describe entities such as products, events, people, books, recipes, and more.


Embedding JSON-LD in Next.js Pages


The recommended approach is to render JSON-LD as a <script type="application/ld+json"> tag inside your layout.tsx or page.tsx components.

Example:

export default async function Page({ params }) {
  const { id } = await params
  const product = await getProduct(id)

  const jsonLd = {
    '@context': 'https://schema.org',
    '@type': 'Product',
    name: product.name,
    image: product.image,
    description: product.description,
  }

  return (
    <section>
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
        }}
      />
      {/* Other page content */}
    </section>
  )
}

Preventing XSS Vulnerabilities


JSON.stringify does not sanitize malicious strings. To prevent XSS injection, replace characters like < with their Unicode equivalents (e.g. \u003c) or use libraries like serialize-javascript for safer serialization.


Typing JSON-LD with TypeScript


Use community packages like schema-dts to type your JSON-LD objects:

import { Product, WithContext } from 'schema-dts'

const jsonLd: WithContext<Product> = {
  '@context': 'https://schema.org',
  '@type': 'Product',
  name: 'Next.js Sticker',
  image: 'https://nextjs.org/imgs/sticker.png',
  description: 'Dynamic at the speed of static.',
}

Validating Structured Data


Use the following tools to test and validate your JSON-LD:


Conclusion


Adding JSON-LD to your Next.js application improves SEO and helps search engines understand your content. By embedding structured data securely and using TypeScript for validation, you can deliver rich, machine-readable pages with confidence.


Written & researched by Dr. Shahin Siami