N Next.js 中文
原文 ↗

如何在你的 Next.js 应用中实现 JSON-LD

了解如何为你的 Next.js 应用添加 JSON-LD,以便向搜索引擎和 AI 描述你的内容。

更新于 2026-03-02Next.js 16.4.6

JSON-LD 是一种结构化数据格式,搜索引擎和 AI 可以用它来帮助理解页面结构,而不仅仅理解页面内容本身。例如,你可以用它来描述人物、事件、组织、电影、书籍、食谱以及许多其他类型的实体。

目前我们推荐的 JSON-LD 做法是在 layout.js 或 page.js 组件中以 <script> 标签的形式渲染结构化数据。

以下代码片段使用了 JSON.stringify,它不会对 XSS 注入中使用的恶意字符串进行净化处理。为了防止这类漏洞,你可以从 JSON-LD 负载中清理 HTML 标签,例如把字符 < 替换为其对应的 Unicode 等价形式 \u003c。

请查阅你所在组织推荐的、用于净化潜在危险字符串的方法,或者为 JSON.stringify 使用社区维护的替代方案,例如 serialize-javascript。

TypeScript

app/products/[id]/page.tsxtsx
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>
      {/* Add JSON-LD to your page */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
        }}
      />
      {/* ... */}
    </section>
  )
}

JavaScript

app/products/[id]/page.jsjsx
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>
      {/* Add JSON-LD to your page */}
      <script
        type="application/ld+json"
        dangerouslySetInnerHTML={{
          __html: JSON.stringify(jsonLd).replace(/</g, '\\u003c'),
        }}
      />
      {/* ... */}
    </section>
  )
}

你可以使用 Google 的 Rich Results Test 或通用的 Schema Markup Validator 来验证和测试你的结构化数据。

你可以借助社区包(例如 schema-dts)用 TypeScript 为你的 JSON-LD 添加类型:

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.',
}

值得了解:

next/script 组件针对 JavaScript 的加载和执行进行了优化。由于 JSON-LD 是结构化数据而非可执行代码,因此在这里使用原生的 <script> 标签才是合适的选择。