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

NextJS自定义pages/404.ts未生效,如何替换默认404页面

问题原因

你当前使用的next/error是Next.js内置的通用错误组件,默认不会关联你自定义的pages/404.ts页面,只有路由匹配失败、或你主动触发框架内置的404逻辑时,才会加载自定义的404页面。

解决方案

根据你的数据获取场景,选择对应处理方式即可:

方案1:服务端数据获取阶段触发(推荐)

如果organization是在getServerSideProps/getStaticProps中获取的,直接在数据为空时返回notFound配置,框架会自动加载自定义404页面:

export async function getServerSideProps(context) {
  // 你的organization获取逻辑
  const organization = await fetchOrgData(context.params.slug)
  if (!organization) {
    return {
      notFound: true
    }
  }
  return {
    props: { organization }
  }
}

方案2:客户端渲染阶段触发

如果organization是客户端请求获取的,两种可选写法:

  • 直接导入自定义404组件返回:
// 导入你自己写的404组件
import NotFound from 'pages/404'
import type { NextPage } from 'next'

const Slug: NextPage<SlugProps> = ({ organization }) => {
  if (!organization) {
    return <NotFound />
  }
  return <h1>{organization.name}</h1>
}
  • 调用框架内置的notFound()方法(Next.js 10+ 支持),会中断渲染直接加载自定义404页:
import { notFound } from 'next/navigation'
import type { NextPage } from 'next'

const Slug: NextPage<SlugProps> = ({ organization }) => {
  if (!organization) {
    notFound()
  }
  return <h1>{organization.name}</h1>
}

如果是Next.js 10之前的版本,可用路由跳转方式实现:

import { useRouter } from 'next/router'
import { useEffect } from 'react'
import type { NextPage } from 'next'

const Slug: NextPage<SlugProps> = ({ organization }) => {
  const router = useRouter()
  useEffect(() => {
    if (!organization) {
      router.push('/404')
    }
  }, [organization, router])

  if (!organization) return null
  return <h1>{organization.name}</h1>
}
注意事项

自定义404页面必须放在pages目录根路径下,文件名为404.ts/404.tsx,不能放在子目录中,否则框架无法自动识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:36:01