如何为Next.js自定义404页面设置正确的404响应状态码
Next.js 自定义404页面返回404状态码解决方案
1 修复动态路由页面的404判断逻辑
你现有的getStaticProps代码存在逻辑顺序错误,且没有使用Next.js官方提供的notFound配置,修正后代码如下:
export async function getStaticProps({ params: { id } }) { const res = await fetchContentfulPosts(); const posts = await res .filter((r) => r.sys.id === id) .map((p) => { return { fields: p.fields, locale: p.sys.locale, tags: p.metadata.tags, }; }); // 将非空判断移到解构操作前,找不到对应内容直接返回notFound配置 if (!posts || posts.length === 0) { return { notFound: true, // 该配置会自动触发404页面,同时自动将响应状态码设为404,无需手动重定向 }; } const { locale, fields, tags } = posts[0]; const { title, author, date, image, text, shareDesc } = fields; return { props: { title, author, date, text, image: image || null, locale, tags, shareDesc }, }; }
notFound: true是Next.js专门为SSG/ISR页面提供的原生配置,返回后会自动加载自定义404页面,不会产生多余的跳转,也能保证状态码正确。
2 全局未知路由的404状态码配置
如果你使用的是Pages Router,不需要依赖_error.js处理全局404,直接在pages根目录下新建404.js文件,写入你的自定义404页面代码即可:
import { Layout, NotFoundComponent } from '../components'; export default function Custom404() { return ( <Layout title="404: This page could not be found" backgroundVideo noIndex> <NotFoundComponent /> </Layout> ); }
Next.js会自动将所有未匹配到现有路由的请求指向该页面,同时默认返回404响应状态码,无需额外手动配置状态码。
3 App Router项目适配方案
如果你使用的是Next.js 13+的App Router,只需要在app目录下新建not-found.js文件写入自定义404内容,Next.js会自动处理所有未匹配路由和主动触发的notFound请求,默认返回404状态码。在逻辑中主动触发404可以使用next/navigation提供的notFound()方法:
import { notFound } from 'next/navigation'; async function getPost(id) { const res = await fetchContentfulPosts(id); if (!res) notFound(); return res; }
内容的提问来源于stack exchange,提问作者seven
相关产品推荐
相关产品推荐

