Next.js中如何实现返回404状态码的自定义404页面?
Next.js Catch-All页面返回404状态码的实现方案
项目文件夹结构

当前代码(/[...catchAll]/page.js)
import PageTransition from "@/components/PageTransition"; import { pageContent } from "@/utils/content"; import { usePathname } from "next/navigation"; export default function CatchAll() { const pathname = usePathname(); const blocks = pageContent?.[pathname]; return ( <> {!blocks ? ( <PageTransition> <main> <h1>404 NOT FOUND</h1> <p> This page does not exist. Please check the URL and try again. </p> </main> </PageTransition> ) : ( <> {blocks.map((block, index) => ( <block.component {...block.componentProps} key={index}> {block.content} </block.component> ))} </> )} </> ); }
问题说明
当前访问不存在的URL时,页面会显示404提示内容,但HTTP响应状态码仍为200 OK,需要修改为返回404状态码。
解决方案
在Next.js App Router中,可通过官方提供的notFound函数触发404状态码,同时可配合自定义404页面实现需求:
步骤1:修改CatchAll组件逻辑
导入notFound函数,在判断无对应内容时调用该函数,让Next.js自动设置404状态码:
import PageTransition from "@/components/PageTransition"; import { pageContent } from "@/utils/content"; import { usePathname } from "next/navigation"; import { notFound } from 'next/navigation'; // 导入notFound函数 export default function CatchAll() { const pathname = usePathname(); const blocks = pageContent?.[pathname]; // 无对应内容时触发404 if (!blocks) { notFound(); } return ( <> {blocks.map((block, index) => ( <block.component {...block.componentProps} key={index}> {block.content} </block.component> ))} </> ); }
步骤2:自定义404页面(可选)
若需要保留原有的404提示样式,可在app目录下创建not-found.js文件,编写自定义404页面内容:
import PageTransition from "@/components/PageTransition"; export default function NotFound() { return ( <PageTransition> <main> <h1>404 NOT FOUND</h1> <p>该页面不存在,请检查URL后重试。</p> </main> </PageTransition> ); }
当调用notFound()时,Next.js会自动渲染这个自定义页面,并返回404状态码。
原理说明
之前的代码仅通过条件渲染展示了404内容,但未告知Next.js这是一个不存在的页面,因此默认返回200状态码。调用notFound()后,Next.js会正确设置HTTP响应状态码为404,同时触发404页面的渲染。
内容的提问来源于stack exchange,提问作者chagatai
相关产品推荐
相关产品推荐

