NNext.js 中文网 GitHub

not-found.js

not-found.js 文件的 API 参考。

Next.js 提供了两种约定来处理未找到的情况:

  • not-found.js:当你在路由段中调用 notFound 函数时使用。
  • global-not-found.js:用于为整个应用中未匹配的路由定义全局 404 页面。这在路由层面处理,不依赖于渲染布局或页面。

not-found.js#

当 notFound 函数在路由段中被抛出时,not-found 文件会渲染 UI。

在流式传输开始之前,Next.js 返回 404 状态码。流式传输开始后,状态码保持为 200,未找到的 UI 会在响应中渲染。这两种情况下 Next.js 都会注入 <meta name="robots" content="noindex" /> 标签。有关详情,请参阅状态码。

app/not-found.tsx
import Link from 'next/link'

export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  )
}
app/blog/not-found.js
import Link from 'next/link'

export default function NotFound() {
  return (
    <div>
      <h2>Not Found</h2>
      <p>Could not find requested resource</p>
      <Link href="/">Return Home</Link>
    </div>
  )
}

在组件层次结构中,not-found.js 在 loading.js 和 page.js 之间渲染。它被同一段中 loading.js 的 <Suspense> 边界和 error.js 的错误边界所包裹。

小知识:默认的未找到 UI 通过 prefers-color-scheme 遵循操作系统的配色方案,不会读取应用级别的主题(例如 <html> 上的 class 或 data-theme 属性)。由于它渲染在根布局内部,匹配显式主题的最快方法是在全局样式表中添加一对更高优先级的规则,并限定在你的主题选择器范围内——例如 html[data-theme='light'] body 和 html[data-theme='dark'] body。要完全控制标记,请提供你自己的 not-found.js。

global-not-found.js(实验性)#

global-not-found.js 文件可让你为整个应用定义 404 页面。与在路由级别工作的 not-found.js 不同,它用于请求的 URL 根本不匹配任何路由的情况。Next.js 会跳过渲染并直接返回这个全局页面。

global-not-found.js 文件会绕过应用的正常渲染,这意味着你需要导入 404 页面所需的任何全局样式、字体或其他依赖。这包括你的主题:由于 global-not-found.js 绕过了布局,操作系统配色方案是默认 UI 唯一能看到的信号,因此请在此文件内应用你的主题(class 或属性)。

小知识:较小版本的全局样式和更简单的字体族可以提高此页面的性能。

当无法使用 layout.js 和 not-found.js 组合构建 404 页面时,global-not-found.js 很有用。这可能发生在以下两种情况:

  • 你的应用有多个根布局(例如 app/(admin)/layout.tsx 和 app/(shop)/layout.tsx),因此没有单一布局可用于组合全局 404。
  • 你的根布局使用顶层动态段定义(例如 app/[country]/layout.tsx),这使得组合一致的 404 页面更加困难。

要启用它,请在 next.config.ts 中添加 globalNotFound 标志:

next.config.ts
import type { NextConfig } from 'next'

const nextConfig: NextConfig = {
  experimental: {
    globalNotFound: true,
  },
}

export default nextConfig

然后,在 app 目录的根目录下创建一个文件:app/global-not-found.js:

app/global-not-found.tsx
// 导入全局样式和字体
import './globals.css'
import { Inter } from 'next/font/google'
import type { Metadata } from 'next'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: '404 - Page Not Found',
  description: 'The page you are looking for does not exist.',
}

export default function GlobalNotFound() {
  return (
    <html lang="en" className={inter.className}>
      <body>
        <h1>404 - Page Not Found</h1>
        <p>This page does not exist.</p>
      </body>
    </html>
  )
}
app/global-not-found.js
// 导入全局样式和字体
import './globals.css'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export const metadata = {
  title: '404 - Page Not Found',
  description: 'The page you are looking for does not exist.',
}

export default function GlobalNotFound() {
  return (
    <html lang="en" className={inter.className}>
      <body>
        <h1>404 - Page Not Found</h1>
        <p>This page does not exist.</p>
      </body>
    </html>
  )
}

与 not-found.js 不同,此文件必须返回完整的 HTML 文档,包括 <html> 和 <body> 标签。

参考#

属性#

not-found.js 或 global-not-found.js 组件不接受任何 props。

小知识:

  • 除了捕获预期的 notFound() 错误外,根 app/not-found.js 和 app/global-not-found.js 文件还会处理整个应用的任何未匹配 URL。这意味着访问未被应用处理的 URL 的用户将看到导出的 UI。
  • Next.js 会将每个 not-found.js 文件与其段下的每个路由一起发送,而不仅仅是与未找到的页面一起发送,并且会在这些页面上加载它导入的 Client Components。对于根 app/not-found.js,那就是应用的每个页面,因此那里应优先使用 Server Components 和 <Link> 而非交互式 UI。

示例#

数据获取#

默认情况下,not-found 是 Server Component。你可以将其标记为 async 以获取并显示数据:

app/not-found.tsx
import Link from 'next/link'
import { headers } from 'next/headers'

export default async function NotFound() {
  const headersList = await headers()
  const domain = headersList.get('host')
  const data = await getSiteData(domain)
  return (
    <div>
      <h2>Not Found: {data.name}</h2>
      <p>Could not find requested resource</p>
      <p>
        View <Link href="/blog">all posts</Link>
      </p>
    </div>
  )
}
app/not-found.jsx
import Link from 'next/link'
import { headers } from 'next/headers'

export default async function NotFound() {
  const headersList = await headers()
  const domain = headersList.get('host')
  const data = await getSiteData(domain)
  return (
    <div>
      <h2>Not Found: {data.name}</h2>
      <p>Could not find requested resource</p>
      <p>
        View <Link href="/blog">all posts</Link>
      </p>
    </div>
  )
}

如果你需要使用 usePathname 等 Client Component hook 来基于路径显示内容,则必须在客户端获取数据。

元数据#

根 app/not-found.js 和 app/global-not-found.js 都支持导出 metadata 对象或 generateMetadata 函数,以自定义 404 页面的 <title>、<meta> 和其他 head 标签:

小知识:对于返回 404 状态码的页面(包括 global-not-found.js 页面),Next.js 会自动注入 <meta name="robots" content="noindex" />。

app/global-not-found.tsx
import type { Metadata } from 'next'

export const metadata: Metadata = {
  title: 'Not Found',
  description: 'The page you are looking for does not exist.',
}

export default function GlobalNotFound() {
  return (
    <html lang="en">
      <body>
        <div>
          <h1>Not Found</h1>
          <p>The page you are looking for does not exist.</p>
        </div>
      </body>
    </html>
  )
}
app/global-not-found.js
export const metadata = {
  title: 'Not Found',
  description: 'The page you are looking for does not exist.',
}

export default function GlobalNotFound() {
  return (
    <html lang="en">
      <body>
        <div>
          <h1>Not Found</h1>
          <p>The page you are looking for does not exist.</p>
        </div>
      </body>
    </html>
  )
}

版本历史#

版本变更
v15.4.0引入 global-not-found.js(实验性)。
v13.3.0根 app/not-found 处理全局未匹配的 URL。
v13.0.0引入 not-found。
Next.js 中文网