如何在 Next.js 13 应用程序路由器中添加架构

and*_*lla 3 javascript schema app-router next.js next.js13

太长了;博士

Next.js 13 的/app路由器layoutpage路由改变了我们向<head>. 如何向每个页面添加架构脚本?Next.js 会自动将<head>放置在任何layoutpage中的标签编译为单个<head>.

目标

就像任何具有出色 SEO 的网站一样,我想在每个页面的头部包含一个架构脚本。

历史

通常,这就像这样简单地编写<head>

<!-- index.html -->
<head>
  <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      // ... the rest
    }
  </script>
</head>
Run Code Online (Sandbox Code Playgroud)

然后,Next.js/pages目录有点不同。我总是觉得必须使用该dangerouslySetInnerHTML属性很奇怪,但至少它有效。

// index.tsx
import Head from 'next/head'
export default function Page() {
  return (
    <Head>
      <script id="schema" type="application/ld+json" dangerouslySetInnerHTML={{__html: `
        {
          "@context": "https://schema.org",
          // ... the rest
        }
      `}} />
    </Head>
  )
}
Run Code Online (Sandbox Code Playgroud)

问题

现在,随着路由器的引入/app,我们有了很棒的、新的、简化的方法来设置元数据,而无需直接导入<head>through next/head. 事实上,该next/head组件不应该在/app路由器中使用。

所以问题就变成了……

我们如何<head>逐页访问?

我希望 Next.js 团队已经考虑到这一点,并将模式添加到新metadata变量,甚至它自己的变量中,但据我所知,他们似乎没有计划这样做。

我尝试添加 a<head>page,不幸的是,它没有正确合并到<head>. 到目前为止,我唯一能做的就是将架构添加到每个页面layout,但是为每个页面都有单独的布局将是多么麻烦。

欢迎任何想法。

and*_*lla 6

Next.js 官方答案

\n

Next.js 团队在Metadata \xe2\x80\x93 JSON-LD中有关于此的官方文档。<head>(不需要将架构放在 中,如代码所示)

\n

代码示例

\n

使用 JS 对象和<script>标签,我们可以在任何页面上添加 JSON-LD。

\n
// page.tsx\n\nexport default async function Page({ params }) {\n  const product = await getProduct(params.id)\n \n  const jsonLd = {\n    \'@context\': \'https://schema.org\',\n    \'@type\': \'Product\',\n    name: product.name,\n    image: product.image,\n    description: product.description,\n  }\n \n  return (\n    <section>\n      {/* Add JSON-LD to your page */}\n      <script\n        type="application/ld+json"\n        dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}\n      />\n      {/* ... */}\n    </section>\n  )\n}\n
Run Code Online (Sandbox Code Playgroud)\n