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

如何在Next.js 13中设置动态Meta关键词与作者?求解决方案

解决Next.js 13 App Router中动态Meta关键词与作者的设置问题

你之前的写法错误在于:Next.js 13的metadata对象里,只有title和description支持{ default, template }的结构实现动态拼接,keywords、authors这类元数据字段并不支持这种template语法。下面是两种可行的解决方案:


方案1:在路由页面中覆盖默认元数据

在具体的路由页面(比如app/post/[slug]/page.js)里定义metadata,直接覆盖layout中设置的默认keywords和authors:

layout.js(修正默认值)

export const metadata = {
  title: {
    default: 'HealthCare Biodiversity',
    template: '%s | HealthCare Biodiversity'
  },
  description: {
    default: 'The Dynamic & Powerful Blog',
    template: '%s | HealthCare Biodiversity'
  },
  referrer: 'origin-when-cross-origin',
  // 仅保留默认值,移除不支持的template结构
  keywords: ['Next.js', 'React', 'JavaScript'],
  authors: [{ name: 'Seb' }]
}

动态页面(以app/post/[slug]/page.js为例)

// 根据路由参数或数据获取动态值
export async function generateMetadata({ params }) {
  // 模拟根据slug获取文章数据
  const post = await getPostBySlug(params.slug);
  
  return {
    // 合并默认关键词与动态标签
    keywords: [...metadata.keywords, ...post.tags],
    authors: [{ name: post.author }]
  }
}

// 模拟数据获取函数
async function getPostBySlug(slug) {
  return {
    tags: ['Ecology', 'Conservation'],
    author: 'Jane Doe'
  }
}

export default function PostPage({ params }) {
  return <div>文章内容</div>
}

方案2:在layout中使用generateMetadata函数(全局动态逻辑)

如果需要在layout层面根据路由或全局状态动态生成元数据,可以用generateMetadata替代静态metadata对象:

export async function generateMetadata({ params, searchParams }) {
  // 这里可根据路由参数、全局状态等获取动态值
  const dynamicKeywords = ['Dynamic Content', 'Eco Blog'];
  const dynamicAuthor = 'John Smith';

  return {
    title: {
      default: 'HealthCare Biodiversity',
      template: '%s | HealthCare Biodiversity'
    },
    description: {
      default: 'The Dynamic & Powerful Blog',
      template: '%s | HealthCare Biodiversity'
    },
    referrer: 'origin-when-cross-origin',
    keywords: ['Next.js', 'React', 'JavaScript', ...dynamicKeywords],
    authors: [{ name: dynamicAuthor }]
  }
}

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}

核心注意点:

  • 仅title和description支持default + template的语法,其他元数据字段需直接设置具体值,或通过generateMetadata函数动态生成。
  • 子路由的metadata或generateMetadata会自动合并、覆盖父layout中的元数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 16:24:58