跳到主要内容

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

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

我们目前对 JSON-LD 的建议是在您的 layout.jspage.js 组件中将结构化数据渲染为 <script> 标签。

以下代码片段使用 JSON.stringify,它不会清理 XSS 注入中使用的恶意字符串。为了防止这种类型的漏洞,您可以从 JSON-LD 有效载荷中清理 HTML 标签,例如,将字符 < 替换为其 unicode 等效项 \u003c

查看您组织推荐的清理潜在危险字符串的方法,或使用社区维护的 JSON.stringify 替代方案,例如 serialize-javascript

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

您可以使用 Google 的富结果测试或通用的Schema 标记验证器来验证和测试您的结构化数据。

您可以使用社区包(如 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.',
}