You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13.4 App Router中如何在head内定义Schema SEO标签?

在Next.js 13.4 App Router中处理Schema SEO标记的位置问题

要不要在意Schema放在body里?

从SEO规范和最佳实践来看,Schema标记放在<head>中是W3C推荐的标准位置,更符合网页结构规范。不过实际层面,主流搜索引擎(包括Google)都支持读取<body>中的Schema数据,不会直接影响你的页面收录或排名。但如果你追求代码的规范性、想要遵循最佳实践,还是建议把Schema放到<head>中,避免一些潜在的边缘兼容性问题。

如何将Schema放入head中?

App Router已经废弃了传统的next/head组件,你可以通过以下两种方式实现:

方法1:利用Metadata的scripts字段

在layout.tsx或page.tsx中导出metadata对象,通过scripts属性添加Schema脚本,它会自动被注入到页面的<head>里:

import type { Metadata } from 'next'

export const metadata: Metadata = {
  scripts: [
    {
      type: 'application/ld+json',
      dangerouslySetInnerHTML: {
        __html: JSON.stringify({
          "@context": "https://schema.org",
          "@type": "Website",
          "name": "你的网站名称",
          "description": "网站描述",
          // 这里添加你的其他Schema字段
        })
      }
    }
  ]
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="zh-CN">
      <body>{children}</body>
    </html>
  )
}

方法2:使用next/script组件直接插入head

在layout.tsx的<head>标签中使用next/script组件,指定strategy="beforeInteractive"确保脚本被注入到head中:

import Script from 'next/script'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const schemaData = {
    "@context": "https://schema.org",
    "@type": "Website",
    "name": "你的网站名称",
    "description": "网站描述",
    // 扩展你的Schema内容
  }

  return (
    <html lang="zh-CN">
      <head>
        <Script
          type="application/ld+json"
          strategy="beforeInteractive"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(schemaData) }}
        />
      </head>
      <body>{children}</body>
    </html>
  )
}

注意:如果是动态生成的Schema数据(比如从API获取),可以在Server Component中直接生成JSON字符串,再通过上述方式注入。

内容的提问来源于stack exchange,提问作者Obiwan Kenewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 17:30:16