not-found.js

not-found 檔案用於在路由區段內拋出 notFound 函數時渲染 UI。除了提供自訂 UI 外,Next.js 會針對串流回應傳回 200 HTTP 狀態碼,非串流回應則傳回 404

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>
  )
}

須知事項:除了捕捉預期的 notFound() 錯誤外,根目錄的 app/not-found.js 檔案還會處理應用程式中所有未匹配的 URL。這表示使用者造訪應用程式未處理的 URL 時,將會看到由 app/not-found.js 檔案匯出的 UI。

Props

not-found.js 元件不接受任何 props。

資料獲取

預設情況下,not-found 是一個伺服器元件 (Server Component)。您可以將其標記為 async 以獲取並顯示資料:

import Link from 'next/link'
import { headers } from 'next/headers'

export default async function NotFound() {
  const headersList = 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>
  )
}

版本歷史

版本變更內容
v13.3.0根目錄 app/not-found 處理全域未匹配的 URL。
v13.0.0引入 not-found 功能。

On this page