NextJS中如何在not-found.tsx中正确配置元数据?
在Next.js App Router中正确配置NotFound页面元数据
如果你的根目录not-found.tsx导出的Metadata未生效,可按以下步骤排查修复:
1. 确认Next.js版本
确保项目使用Next.js v13.4.0及以上版本,早期版本的App Router对not-found.tsx的元数据支持存在局限性。
2. 正确导出静态Metadata对象
在not-found.tsx中,与组件默认导出同级,直接导出静态metadata对象,示例代码:
import React from 'react'; // 与组件同级导出metadata export const metadata = { title: 'Page not found', description: 'The page you are looking for does not exist.' }; export default function NotFound() { return ( <div className="container"> <h1>404 - Page Not Found</h1> <p>Sorry, we couldn't find the page you're looking for.</p> </div> ); }
3. 改用generateMetadata函数(静态导出失效时)
若静态导出仍不生效,可尝试使用动态的generateMetadata函数,确保元数据被正确注入:
import React from 'react'; import type { Metadata } from 'next'; export async function generateMetadata(): Promise<Metadata> { return { title: 'Page not found', description: 'The requested page does not exist.' }; } export default function NotFound() { return ( <div> <h1>404 - Not Found</h1> </div> ); }
4. 排除干扰因素
- 移除项目中旧的
next/head用法:App Router下Metadata API会自动管理head标签,无需手动引入next/head。 - 检查上层
layout.tsx的元数据配置:如果布局中设置了titleTemplate(如%s | My App),需确保NotFound页面的标题能正确覆盖或适配模板;若需要完全自定义标题,可在generateMetadata中返回完整标题字符串。 - 清除浏览器缓存并重新构建项目:缓存可能导致元数据未更新,执行
npm run build后再启动项目测试。
内容的提问来源于stack exchange,提问作者netrolite
相关产品推荐
相关产品推荐

